babylon.max.js 4.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. /** @hidden */
  190. this._bonesComputationForcedToCPU = false;
  191. this._uniformBuffersNames = {};
  192. this._isReady = false;
  193. this._compilationError = "";
  194. this.name = baseName;
  195. if (attributesNamesOrOptions.attributes) {
  196. var options = attributesNamesOrOptions;
  197. this._engine = uniformsNamesOrEngine;
  198. this._attributesNames = options.attributes;
  199. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  200. this._samplers = options.samplers.slice();
  201. this.defines = options.defines;
  202. this.onError = options.onError;
  203. this.onCompiled = options.onCompiled;
  204. this._fallbacks = options.fallbacks;
  205. this._indexParameters = options.indexParameters;
  206. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  207. if (options.uniformBuffersNames) {
  208. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  209. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  210. }
  211. }
  212. }
  213. else {
  214. this._engine = engine;
  215. this.defines = defines;
  216. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  217. this._samplers = samplers ? samplers.slice() : [];
  218. this._attributesNames = attributesNamesOrOptions;
  219. this.onError = onError;
  220. this.onCompiled = onCompiled;
  221. this._indexParameters = indexParameters;
  222. this._fallbacks = fallbacks;
  223. }
  224. this.uniqueId = Effect._uniqueIdSeed++;
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. this._loadVertexShader(vertexSource, function (vertexCode) {
  246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  247. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  250. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  251. if (baseName) {
  252. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  253. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  254. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  255. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  256. }
  257. else {
  258. _this._vertexSourceCode = migratedVertexCode;
  259. _this._fragmentSourceCode = migratedFragmentCode;
  260. }
  261. _this._prepareEffect();
  262. });
  263. });
  264. });
  265. });
  266. });
  267. });
  268. }
  269. Object.defineProperty(Effect.prototype, "key", {
  270. /**
  271. * Unique key for this effect
  272. */
  273. get: function () {
  274. return this._key;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. /**
  280. * If the effect has been compiled and prepared.
  281. * @returns if the effect is compiled and prepared.
  282. */
  283. Effect.prototype.isReady = function () {
  284. return this._isReady;
  285. };
  286. /**
  287. * The engine the effect was initialized with.
  288. * @returns the engine.
  289. */
  290. Effect.prototype.getEngine = function () {
  291. return this._engine;
  292. };
  293. /**
  294. * The compiled webGL program for the effect
  295. * @returns the webGL program.
  296. */
  297. Effect.prototype.getProgram = function () {
  298. return this._program;
  299. };
  300. /**
  301. * The set of names of attribute variables for the shader.
  302. * @returns An array of attribute names.
  303. */
  304. Effect.prototype.getAttributesNames = function () {
  305. return this._attributesNames;
  306. };
  307. /**
  308. * Returns the attribute at the given index.
  309. * @param index The index of the attribute.
  310. * @returns The location of the attribute.
  311. */
  312. Effect.prototype.getAttributeLocation = function (index) {
  313. return this._attributes[index];
  314. };
  315. /**
  316. * Returns the attribute based on the name of the variable.
  317. * @param name of the attribute to look up.
  318. * @returns the attribute location.
  319. */
  320. Effect.prototype.getAttributeLocationByName = function (name) {
  321. var index = this._attributesNames.indexOf(name);
  322. return this._attributes[index];
  323. };
  324. /**
  325. * The number of attributes.
  326. * @returns the numnber of attributes.
  327. */
  328. Effect.prototype.getAttributesCount = function () {
  329. return this._attributes.length;
  330. };
  331. /**
  332. * Gets the index of a uniform variable.
  333. * @param uniformName of the uniform to look up.
  334. * @returns the index.
  335. */
  336. Effect.prototype.getUniformIndex = function (uniformName) {
  337. return this._uniformsNames.indexOf(uniformName);
  338. };
  339. /**
  340. * Returns the attribute based on the name of the variable.
  341. * @param uniformName of the uniform to look up.
  342. * @returns the location of the uniform.
  343. */
  344. Effect.prototype.getUniform = function (uniformName) {
  345. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  346. };
  347. /**
  348. * Returns an array of sampler variable names
  349. * @returns The array of sampler variable neames.
  350. */
  351. Effect.prototype.getSamplers = function () {
  352. return this._samplers;
  353. };
  354. /**
  355. * The error from the last compilation.
  356. * @returns the error string.
  357. */
  358. Effect.prototype.getCompilationError = function () {
  359. return this._compilationError;
  360. };
  361. /**
  362. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  363. * @param func The callback to be used.
  364. */
  365. Effect.prototype.executeWhenCompiled = function (func) {
  366. if (this.isReady()) {
  367. func(this);
  368. return;
  369. }
  370. this.onCompileObservable.add(function (effect) {
  371. func(effect);
  372. });
  373. };
  374. /** @hidden */
  375. Effect.prototype._loadVertexShader = function (vertex, callback) {
  376. if (BABYLON.Tools.IsWindowObjectExist()) {
  377. // DOM element ?
  378. if (vertex instanceof HTMLElement) {
  379. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  380. callback(vertexCode);
  381. return;
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (vertex.substr(0, 7) === "base64:") {
  386. var vertexBinary = window.atob(vertex.substr(7));
  387. callback(vertexBinary);
  388. return;
  389. }
  390. // Is in local store ?
  391. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  392. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  393. return;
  394. }
  395. var vertexShaderUrl;
  396. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  397. vertexShaderUrl = vertex;
  398. }
  399. else {
  400. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  401. }
  402. // Vertex shader
  403. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  404. };
  405. /** @hidden */
  406. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  407. if (BABYLON.Tools.IsWindowObjectExist()) {
  408. // DOM element ?
  409. if (fragment instanceof HTMLElement) {
  410. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  411. callback(fragmentCode);
  412. return;
  413. }
  414. }
  415. // Base64 encoded ?
  416. if (fragment.substr(0, 7) === "base64:") {
  417. var fragmentBinary = window.atob(fragment.substr(7));
  418. callback(fragmentBinary);
  419. return;
  420. }
  421. // Is in local store ?
  422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  424. return;
  425. }
  426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  428. return;
  429. }
  430. var fragmentShaderUrl;
  431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  432. fragmentShaderUrl = fragment;
  433. }
  434. else {
  435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  436. }
  437. // Fragment shader
  438. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  439. };
  440. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  441. // Rebuild shaders source code
  442. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  443. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  444. vertexCode = prefix + vertexCode;
  445. fragmentCode = prefix + fragmentCode;
  446. // Number lines of shaders source code
  447. var i = 2;
  448. var regex = /\n/gm;
  449. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  450. i = 2;
  451. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. // Dump shaders name and formatted source code
  453. if (this.name.vertexElement) {
  454. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  455. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  456. }
  457. else if (this.name.vertex) {
  458. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  459. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  460. }
  461. else {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  464. }
  465. };
  466. ;
  467. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  468. var preparedSourceCode = this._processPrecision(sourceCode);
  469. if (this._engine.webGLVersion == 1) {
  470. callback(preparedSourceCode);
  471. return;
  472. }
  473. // Already converted
  474. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  475. callback(preparedSourceCode.replace("#version 300 es", ""));
  476. return;
  477. }
  478. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  479. // Remove extensions
  480. // #extension GL_OES_standard_derivatives : enable
  481. // #extension GL_EXT_shader_texture_lod : enable
  482. // #extension GL_EXT_frag_depth : enable
  483. // #extension GL_EXT_draw_buffers : require
  484. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  485. var result = preparedSourceCode.replace(regex, "");
  486. // Migrate to GLSL v300
  487. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  488. result = result.replace(/attribute[ \t]/g, "in ");
  489. result = result.replace(/[ \t]attribute/g, " in");
  490. if (isFragment) {
  491. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  492. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/texture2D\s*\(/g, "texture(");
  494. result = result.replace(/textureCube\s*\(/g, "texture(");
  495. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  496. result = result.replace(/gl_FragColor/g, "glFragColor");
  497. result = result.replace(/gl_FragData/g, "glFragData");
  498. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  499. }
  500. callback(result);
  501. };
  502. Effect.prototype._processIncludes = function (sourceCode, callback) {
  503. var _this = this;
  504. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  505. var match = regex.exec(sourceCode);
  506. var returnValue = new String(sourceCode);
  507. while (match != null) {
  508. var includeFile = match[1];
  509. // Uniform declaration
  510. if (includeFile.indexOf("__decl__") !== -1) {
  511. includeFile = includeFile.replace(/__decl__/, "");
  512. if (this._engine.supportsUniformBuffers) {
  513. includeFile = includeFile.replace(/Vertex/, "Ubo");
  514. includeFile = includeFile.replace(/Fragment/, "Ubo");
  515. }
  516. includeFile = includeFile + "Declaration";
  517. }
  518. if (Effect.IncludesShadersStore[includeFile]) {
  519. // Substitution
  520. var includeContent = Effect.IncludesShadersStore[includeFile];
  521. if (match[2]) {
  522. var splits = match[3].split(",");
  523. for (var index = 0; index < splits.length; index += 2) {
  524. var source = new RegExp(splits[index], "g");
  525. var dest = splits[index + 1];
  526. includeContent = includeContent.replace(source, dest);
  527. }
  528. }
  529. if (match[4]) {
  530. var indexString = match[5];
  531. if (indexString.indexOf("..") !== -1) {
  532. var indexSplits = indexString.split("..");
  533. var minIndex = parseInt(indexSplits[0]);
  534. var maxIndex = parseInt(indexSplits[1]);
  535. var sourceIncludeContent = includeContent.slice(0);
  536. includeContent = "";
  537. if (isNaN(maxIndex)) {
  538. maxIndex = this._indexParameters[indexSplits[1]];
  539. }
  540. for (var i = minIndex; i < maxIndex; i++) {
  541. if (!this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  548. }
  549. }
  550. else {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent = includeContent.replace(/\{X\}/g, indexString);
  558. }
  559. }
  560. // Replace
  561. returnValue = returnValue.replace(match[0], includeContent);
  562. }
  563. else {
  564. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  565. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  566. Effect.IncludesShadersStore[includeFile] = fileContent;
  567. _this._processIncludes(returnValue, callback);
  568. });
  569. return;
  570. }
  571. match = regex.exec(sourceCode);
  572. }
  573. callback(returnValue);
  574. };
  575. Effect.prototype._processPrecision = function (source) {
  576. if (source.indexOf("precision highp float") === -1) {
  577. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  578. source = "precision mediump float;\n" + source;
  579. }
  580. else {
  581. source = "precision highp float;\n" + source;
  582. }
  583. }
  584. else {
  585. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  586. source = source.replace("precision highp float", "precision mediump float");
  587. }
  588. }
  589. return source;
  590. };
  591. /**
  592. * Recompiles the webGL program
  593. * @param vertexSourceCode The source code for the vertex shader.
  594. * @param fragmentSourceCode The source code for the fragment shader.
  595. * @param onCompiled Callback called when completed.
  596. * @param onError Callback called on error.
  597. */
  598. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  599. var _this = this;
  600. this._isReady = false;
  601. this._vertexSourceCodeOverride = vertexSourceCode;
  602. this._fragmentSourceCodeOverride = fragmentSourceCode;
  603. this.onError = function (effect, error) {
  604. if (onError) {
  605. onError(error);
  606. }
  607. };
  608. this.onCompiled = function () {
  609. var scenes = _this.getEngine().scenes;
  610. for (var i = 0; i < scenes.length; i++) {
  611. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  612. }
  613. if (onCompiled) {
  614. onCompiled(_this._program);
  615. }
  616. };
  617. this._fallbacks = null;
  618. this._prepareEffect();
  619. };
  620. /**
  621. * Gets the uniform locations of the the specified variable names
  622. * @param names THe names of the variables to lookup.
  623. * @returns Array of locations in the same order as variable names.
  624. */
  625. Effect.prototype.getSpecificUniformLocations = function (names) {
  626. var engine = this._engine;
  627. return engine.getUniforms(this._program, names);
  628. };
  629. /**
  630. * Prepares the effect
  631. */
  632. Effect.prototype._prepareEffect = function () {
  633. var attributesNames = this._attributesNames;
  634. var defines = this.defines;
  635. var fallbacks = this._fallbacks;
  636. this._valueCache = {};
  637. var previousProgram = this._program;
  638. try {
  639. var engine = this._engine;
  640. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  641. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  642. }
  643. else {
  644. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  645. }
  646. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  647. if (engine.supportsUniformBuffers) {
  648. for (var name in this._uniformBuffersNames) {
  649. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  650. }
  651. }
  652. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  653. this._attributes = engine.getAttributes(this._program, attributesNames);
  654. var index;
  655. for (index = 0; index < this._samplers.length; index++) {
  656. var sampler = this.getUniform(this._samplers[index]);
  657. if (sampler == null) {
  658. this._samplers.splice(index, 1);
  659. index--;
  660. }
  661. }
  662. engine.bindSamplers(this);
  663. this._compilationError = "";
  664. this._isReady = true;
  665. if (this.onCompiled) {
  666. this.onCompiled(this);
  667. }
  668. this.onCompileObservable.notifyObservers(this);
  669. this.onCompileObservable.clear();
  670. // Unbind mesh reference in fallbacks
  671. if (this._fallbacks) {
  672. this._fallbacks.unBindMesh();
  673. }
  674. if (previousProgram) {
  675. this.getEngine()._deleteProgram(previousProgram);
  676. }
  677. }
  678. catch (e) {
  679. this._compilationError = e.message;
  680. // Let's go through fallbacks then
  681. BABYLON.Tools.Error("Unable to compile effect:");
  682. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  683. return " " + uniform;
  684. }));
  685. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  686. return " " + attribute;
  687. }));
  688. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  689. BABYLON.Tools.Error("Error: " + this._compilationError);
  690. if (previousProgram) {
  691. this._program = previousProgram;
  692. this._isReady = true;
  693. if (this.onError) {
  694. this.onError(this, this._compilationError);
  695. }
  696. this.onErrorObservable.notifyObservers(this);
  697. }
  698. if (fallbacks && fallbacks.isMoreFallbacks) {
  699. BABYLON.Tools.Error("Trying next fallback.");
  700. this.defines = fallbacks.reduce(this.defines, this);
  701. this._prepareEffect();
  702. }
  703. else { // Sorry we did everything we can
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. this.onErrorObservable.clear();
  709. // Unbind mesh reference in fallbacks
  710. if (this._fallbacks) {
  711. this._fallbacks.unBindMesh();
  712. }
  713. }
  714. }
  715. };
  716. Object.defineProperty(Effect.prototype, "isSupported", {
  717. /**
  718. * Checks if the effect is supported. (Must be called after compilation)
  719. */
  720. get: function () {
  721. return this._compilationError === "";
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. /**
  727. * Binds a texture to the engine to be used as output of the shader.
  728. * @param channel Name of the output variable.
  729. * @param texture Texture to bind.
  730. */
  731. Effect.prototype._bindTexture = function (channel, texture) {
  732. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  733. };
  734. /**
  735. * Sets a texture on the engine to be used in the shader.
  736. * @param channel Name of the sampler variable.
  737. * @param texture Texture to set.
  738. */
  739. Effect.prototype.setTexture = function (channel, texture) {
  740. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  741. };
  742. /**
  743. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  744. * @param channel Name of the sampler variable.
  745. * @param texture Texture to set.
  746. */
  747. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  748. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  749. };
  750. /**
  751. * Sets an array of textures on the engine to be used in the shader.
  752. * @param channel Name of the variable.
  753. * @param textures Textures to set.
  754. */
  755. Effect.prototype.setTextureArray = function (channel, textures) {
  756. if (this._samplers.indexOf(channel + "Ex") === -1) {
  757. var initialPos = this._samplers.indexOf(channel);
  758. for (var index = 1; index < textures.length; index++) {
  759. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  760. }
  761. }
  762. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  763. };
  764. /**
  765. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  766. * @param channel Name of the sampler variable.
  767. * @param postProcess Post process to get the input texture from.
  768. */
  769. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  770. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  771. };
  772. /**
  773. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  774. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the output texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /** @hidden */
  782. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  783. var cache = this._valueCache[uniformName];
  784. var flag = matrix.updateFlag;
  785. if (cache !== undefined && cache === flag) {
  786. return false;
  787. }
  788. this._valueCache[uniformName] = flag;
  789. return true;
  790. };
  791. /** @hidden */
  792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  793. var cache = this._valueCache[uniformName];
  794. if (!cache) {
  795. cache = [x, y];
  796. this._valueCache[uniformName] = cache;
  797. return true;
  798. }
  799. var changed = false;
  800. if (cache[0] !== x) {
  801. cache[0] = x;
  802. changed = true;
  803. }
  804. if (cache[1] !== y) {
  805. cache[1] = y;
  806. changed = true;
  807. }
  808. return changed;
  809. };
  810. /** @hidden */
  811. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  812. var cache = this._valueCache[uniformName];
  813. if (!cache) {
  814. cache = [x, y, z];
  815. this._valueCache[uniformName] = cache;
  816. return true;
  817. }
  818. var changed = false;
  819. if (cache[0] !== x) {
  820. cache[0] = x;
  821. changed = true;
  822. }
  823. if (cache[1] !== y) {
  824. cache[1] = y;
  825. changed = true;
  826. }
  827. if (cache[2] !== z) {
  828. cache[2] = z;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /** @hidden */
  834. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  835. var cache = this._valueCache[uniformName];
  836. if (!cache) {
  837. cache = [x, y, z, w];
  838. this._valueCache[uniformName] = cache;
  839. return true;
  840. }
  841. var changed = false;
  842. if (cache[0] !== x) {
  843. cache[0] = x;
  844. changed = true;
  845. }
  846. if (cache[1] !== y) {
  847. cache[1] = y;
  848. changed = true;
  849. }
  850. if (cache[2] !== z) {
  851. cache[2] = z;
  852. changed = true;
  853. }
  854. if (cache[3] !== w) {
  855. cache[3] = w;
  856. changed = true;
  857. }
  858. return changed;
  859. };
  860. /**
  861. * Binds a buffer to a uniform.
  862. * @param buffer Buffer to bind.
  863. * @param name Name of the uniform variable to bind to.
  864. */
  865. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  866. var bufferName = this._uniformBuffersNames[name];
  867. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  868. return;
  869. }
  870. Effect._baseCache[bufferName] = buffer;
  871. this._engine.bindUniformBufferBase(buffer, bufferName);
  872. };
  873. /**
  874. * Binds block to a uniform.
  875. * @param blockName Name of the block to bind.
  876. * @param index Index to bind.
  877. */
  878. Effect.prototype.bindUniformBlock = function (blockName, index) {
  879. this._engine.bindUniformBlock(this._program, blockName, index);
  880. };
  881. /**
  882. * Sets an interger value on a uniform variable.
  883. * @param uniformName Name of the variable.
  884. * @param value Value to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setInt = function (uniformName, value) {
  888. var cache = this._valueCache[uniformName];
  889. if (cache !== undefined && cache === value)
  890. return this;
  891. this._valueCache[uniformName] = value;
  892. this._engine.setInt(this.getUniform(uniformName), value);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array on a uniform variable.
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray2 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray2(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array on a uniform variable.
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray2 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray2(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setArray3 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setArray3(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setArray4 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setArray4(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * Sets matrices on a uniform variable.
  1029. * @param uniformName Name of the variable.
  1030. * @param matrices matrices to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1034. if (!matrices) {
  1035. return this;
  1036. }
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets matrix on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param matrix matrix to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1048. if (this._cacheMatrix(uniformName, matrix)) {
  1049. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1050. }
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1066. * @param uniformName Name of the variable.
  1067. * @param matrix matrix to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1071. this._valueCache[uniformName] = null;
  1072. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a float on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param value value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setFloat = function (uniformName, value) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === value)
  1084. return this;
  1085. this._valueCache[uniformName] = value;
  1086. this._engine.setFloat(this.getUniform(uniformName), value);
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a boolean on a uniform variable.
  1091. * @param uniformName Name of the variable.
  1092. * @param bool value to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setBool = function (uniformName, bool) {
  1096. var cache = this._valueCache[uniformName];
  1097. if (cache !== undefined && cache === bool)
  1098. return this;
  1099. this._valueCache[uniformName] = bool;
  1100. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a Vector2 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param vector2 vector2 to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1110. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a float2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param x First float in float2.
  1119. * @param y Second float in float2.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1123. if (this._cacheFloat2(uniformName, x, y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a Vector3 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param vector3 Value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1135. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1136. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a float3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param x First float in float3.
  1144. * @param y Second float in float3.
  1145. * @param z Third float in float3.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1149. if (this._cacheFloat3(uniformName, x, y, z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Vector4 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param vector4 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1161. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a float4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param x First float in float4.
  1170. * @param y Second float in float4.
  1171. * @param z Third float in float4.
  1172. * @param w Fourth float in float4.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1176. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1177. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1178. }
  1179. return this;
  1180. };
  1181. /**
  1182. * Sets a Color3 on a uniform variable.
  1183. * @param uniformName Name of the variable.
  1184. * @param color3 Value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor3 = function (uniformName, color3) {
  1188. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1189. this._engine.setColor3(this.getUniform(uniformName), color3);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @param alpha Alpha value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1201. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1202. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable
  1208. * @param uniformName defines the name of the variable
  1209. * @param color4 defines the value to be set
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1213. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1214. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Resets the cache of effects.
  1220. */
  1221. Effect.ResetCache = function () {
  1222. Effect._baseCache = {};
  1223. };
  1224. Effect._uniqueIdSeed = 0;
  1225. Effect._baseCache = {};
  1226. /**
  1227. * Store of each shader (The can be looked up using effect.key)
  1228. */
  1229. Effect.ShadersStore = {};
  1230. /**
  1231. * Store of each included file for a shader (The can be looked up using effect.key)
  1232. */
  1233. Effect.IncludesShadersStore = {};
  1234. return Effect;
  1235. }());
  1236. BABYLON.Effect = Effect;
  1237. })(BABYLON || (BABYLON = {}));
  1238. //# sourceMappingURL=babylon.effect.js.map
  1239. //# sourceMappingURL=babylon.types.js.map
  1240. var BABYLON;
  1241. (function (BABYLON) {
  1242. var KeyboardEventTypes = /** @class */ (function () {
  1243. function KeyboardEventTypes() {
  1244. }
  1245. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1246. get: function () {
  1247. return KeyboardEventTypes._KEYDOWN;
  1248. },
  1249. enumerable: true,
  1250. configurable: true
  1251. });
  1252. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1253. get: function () {
  1254. return KeyboardEventTypes._KEYUP;
  1255. },
  1256. enumerable: true,
  1257. configurable: true
  1258. });
  1259. KeyboardEventTypes._KEYDOWN = 0x01;
  1260. KeyboardEventTypes._KEYUP = 0x02;
  1261. return KeyboardEventTypes;
  1262. }());
  1263. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1264. var KeyboardInfo = /** @class */ (function () {
  1265. function KeyboardInfo(type, event) {
  1266. this.type = type;
  1267. this.event = event;
  1268. }
  1269. return KeyboardInfo;
  1270. }());
  1271. BABYLON.KeyboardInfo = KeyboardInfo;
  1272. /**
  1273. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1274. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1275. */
  1276. var KeyboardInfoPre = /** @class */ (function (_super) {
  1277. __extends(KeyboardInfoPre, _super);
  1278. function KeyboardInfoPre(type, event) {
  1279. var _this = _super.call(this, type, event) || this;
  1280. _this.skipOnPointerObservable = false;
  1281. return _this;
  1282. }
  1283. return KeyboardInfoPre;
  1284. }(KeyboardInfo));
  1285. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1286. })(BABYLON || (BABYLON = {}));
  1287. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1288. var BABYLON;
  1289. (function (BABYLON) {
  1290. var PointerEventTypes = /** @class */ (function () {
  1291. function PointerEventTypes() {
  1292. }
  1293. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERDOWN;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERUP;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERMOVE;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERWHEEL;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1322. get: function () {
  1323. return PointerEventTypes._POINTERPICK;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1329. get: function () {
  1330. return PointerEventTypes._POINTERTAP;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1336. get: function () {
  1337. return PointerEventTypes._POINTERDOUBLETAP;
  1338. },
  1339. enumerable: true,
  1340. configurable: true
  1341. });
  1342. PointerEventTypes._POINTERDOWN = 0x01;
  1343. PointerEventTypes._POINTERUP = 0x02;
  1344. PointerEventTypes._POINTERMOVE = 0x04;
  1345. PointerEventTypes._POINTERWHEEL = 0x08;
  1346. PointerEventTypes._POINTERPICK = 0x10;
  1347. PointerEventTypes._POINTERTAP = 0x20;
  1348. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1349. return PointerEventTypes;
  1350. }());
  1351. BABYLON.PointerEventTypes = PointerEventTypes;
  1352. var PointerInfoBase = /** @class */ (function () {
  1353. function PointerInfoBase(type, event) {
  1354. this.type = type;
  1355. this.event = event;
  1356. }
  1357. return PointerInfoBase;
  1358. }());
  1359. BABYLON.PointerInfoBase = PointerInfoBase;
  1360. /**
  1361. * This class is used to store pointer related info for the onPrePointerObservable event.
  1362. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1363. */
  1364. var PointerInfoPre = /** @class */ (function (_super) {
  1365. __extends(PointerInfoPre, _super);
  1366. function PointerInfoPre(type, event, localX, localY) {
  1367. var _this = _super.call(this, type, event) || this;
  1368. /**
  1369. * Ray from a pointer if availible (eg. 6dof controller)
  1370. */
  1371. _this.ray = null;
  1372. _this.skipOnPointerObservable = false;
  1373. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1374. return _this;
  1375. }
  1376. return PointerInfoPre;
  1377. }(PointerInfoBase));
  1378. BABYLON.PointerInfoPre = PointerInfoPre;
  1379. /**
  1380. * This type contains all the data related to a pointer event in Babylon.js.
  1381. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1382. */
  1383. var PointerInfo = /** @class */ (function (_super) {
  1384. __extends(PointerInfo, _super);
  1385. function PointerInfo(type, event, pickInfo) {
  1386. var _this = _super.call(this, type, event) || this;
  1387. _this.pickInfo = pickInfo;
  1388. return _this;
  1389. }
  1390. return PointerInfo;
  1391. }(PointerInfoBase));
  1392. BABYLON.PointerInfo = PointerInfo;
  1393. })(BABYLON || (BABYLON = {}));
  1394. //# sourceMappingURL=babylon.pointerEvents.js.map
  1395. var BABYLON;
  1396. (function (BABYLON) {
  1397. BABYLON.ToGammaSpace = 1 / 2.2;
  1398. BABYLON.ToLinearSpace = 2.2;
  1399. BABYLON.Epsilon = 0.001;
  1400. /**
  1401. * Class used to hold a RBG color
  1402. */
  1403. var Color3 = /** @class */ (function () {
  1404. /**
  1405. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1406. * @param r defines the red component (between 0 and 1, default is 0)
  1407. * @param g defines the green component (between 0 and 1, default is 0)
  1408. * @param b defines the blue component (between 0 and 1, default is 0)
  1409. */
  1410. function Color3(
  1411. /**
  1412. * Defines the red component (between 0 and 1, default is 0)
  1413. */
  1414. r,
  1415. /**
  1416. * Defines the green component (between 0 and 1, default is 0)
  1417. */
  1418. g,
  1419. /**
  1420. * Defines the blue component (between 0 and 1, default is 0)
  1421. */
  1422. b) {
  1423. if (r === void 0) { r = 0; }
  1424. if (g === void 0) { g = 0; }
  1425. if (b === void 0) { b = 0; }
  1426. this.r = r;
  1427. this.g = g;
  1428. this.b = b;
  1429. }
  1430. /**
  1431. * Creates a string with the Color3 current values
  1432. * @returns the string representation of the Color3 object
  1433. */
  1434. Color3.prototype.toString = function () {
  1435. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1436. };
  1437. /**
  1438. * Returns the string "Color3"
  1439. * @returns "Color3"
  1440. */
  1441. Color3.prototype.getClassName = function () {
  1442. return "Color3";
  1443. };
  1444. /**
  1445. * Compute the Color3 hash code
  1446. * @returns an unique number that can be used to hash Color3 objects
  1447. */
  1448. Color3.prototype.getHashCode = function () {
  1449. var hash = this.r || 0;
  1450. hash = (hash * 397) ^ (this.g || 0);
  1451. hash = (hash * 397) ^ (this.b || 0);
  1452. return hash;
  1453. };
  1454. // Operators
  1455. /**
  1456. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1457. * @param array defines the array where to store the r,g,b components
  1458. * @param index defines an optional index in the target array to define where to start storing values
  1459. * @returns the current Color3 object
  1460. */
  1461. Color3.prototype.toArray = function (array, index) {
  1462. if (index === undefined) {
  1463. index = 0;
  1464. }
  1465. array[index] = this.r;
  1466. array[index + 1] = this.g;
  1467. array[index + 2] = this.b;
  1468. return this;
  1469. };
  1470. /**
  1471. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1472. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1473. * @returns a new {BABYLON.Color4} object
  1474. */
  1475. Color3.prototype.toColor4 = function (alpha) {
  1476. if (alpha === void 0) { alpha = 1; }
  1477. return new Color4(this.r, this.g, this.b, alpha);
  1478. };
  1479. /**
  1480. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1481. * @returns the new array
  1482. */
  1483. Color3.prototype.asArray = function () {
  1484. var result = new Array();
  1485. this.toArray(result, 0);
  1486. return result;
  1487. };
  1488. /**
  1489. * Returns the luminance value
  1490. * @returns a float value
  1491. */
  1492. Color3.prototype.toLuminance = function () {
  1493. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1494. };
  1495. /**
  1496. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1497. * @param otherColor defines the second operand
  1498. * @returns the new Color3 object
  1499. */
  1500. Color3.prototype.multiply = function (otherColor) {
  1501. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1502. };
  1503. /**
  1504. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1505. * @param otherColor defines the second operand
  1506. * @param result defines the Color3 object where to store the result
  1507. * @returns the current Color3
  1508. */
  1509. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1510. result.r = this.r * otherColor.r;
  1511. result.g = this.g * otherColor.g;
  1512. result.b = this.b * otherColor.b;
  1513. return this;
  1514. };
  1515. /**
  1516. * Determines equality between Color3 objects
  1517. * @param otherColor defines the second operand
  1518. * @returns true if the rgb values are equal to the given ones
  1519. */
  1520. Color3.prototype.equals = function (otherColor) {
  1521. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1522. };
  1523. /**
  1524. * Determines equality between the current Color3 object and a set of r,b,g values
  1525. * @param r defines the red component to check
  1526. * @param g defines the green component to check
  1527. * @param b defines the blue component to check
  1528. * @returns true if the rgb values are equal to the given ones
  1529. */
  1530. Color3.prototype.equalsFloats = function (r, g, b) {
  1531. return this.r === r && this.g === g && this.b === b;
  1532. };
  1533. /**
  1534. * Multiplies in place each rgb value by scale
  1535. * @param scale defines the scaling factor
  1536. * @returns the updated Color3
  1537. */
  1538. Color3.prototype.scale = function (scale) {
  1539. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1540. };
  1541. /**
  1542. * Multiplies the rgb values by scale and stores the result into "result"
  1543. * @param scale defines the scaling factor
  1544. * @param result defines the Color3 object where to store the result
  1545. * @returns the unmodified current Color3
  1546. */
  1547. Color3.prototype.scaleToRef = function (scale, result) {
  1548. result.r = this.r * scale;
  1549. result.g = this.g * scale;
  1550. result.b = this.b * scale;
  1551. return this;
  1552. };
  1553. /**
  1554. * Scale the current Color3 values by a factor and add the result to a given Color3
  1555. * @param scale defines the scale factor
  1556. * @param result defines color to store the result into
  1557. * @returns the unmodified current Color3
  1558. */
  1559. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1560. result.r += this.r * scale;
  1561. result.g += this.g * scale;
  1562. result.b += this.b * scale;
  1563. return this;
  1564. };
  1565. /**
  1566. * Clamps the rgb values by the min and max values and stores the result into "result"
  1567. * @param min defines minimum clamping value (default is 0)
  1568. * @param max defines maximum clamping value (default is 1)
  1569. * @param result defines color to store the result into
  1570. * @returns the original Color3
  1571. */
  1572. Color3.prototype.clampToRef = function (min, max, result) {
  1573. if (min === void 0) { min = 0; }
  1574. if (max === void 0) { max = 1; }
  1575. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1576. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1577. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1578. return this;
  1579. };
  1580. /**
  1581. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1582. * @param otherColor defines the second operand
  1583. * @returns the new Color3
  1584. */
  1585. Color3.prototype.add = function (otherColor) {
  1586. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1587. };
  1588. /**
  1589. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1590. * @param otherColor defines the second operand
  1591. * @param result defines Color3 object to store the result into
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.addToRef = function (otherColor, result) {
  1595. result.r = this.r + otherColor.r;
  1596. result.g = this.g + otherColor.g;
  1597. result.b = this.b + otherColor.b;
  1598. return this;
  1599. };
  1600. /**
  1601. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1602. * @param otherColor defines the second operand
  1603. * @returns the new Color3
  1604. */
  1605. Color3.prototype.subtract = function (otherColor) {
  1606. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1607. };
  1608. /**
  1609. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1610. * @param otherColor defines the second operand
  1611. * @param result defines Color3 object to store the result into
  1612. * @returns the unmodified current Color3
  1613. */
  1614. Color3.prototype.subtractToRef = function (otherColor, result) {
  1615. result.r = this.r - otherColor.r;
  1616. result.g = this.g - otherColor.g;
  1617. result.b = this.b - otherColor.b;
  1618. return this;
  1619. };
  1620. /**
  1621. * Copy the current object
  1622. * @returns a new Color3 copied the current one
  1623. */
  1624. Color3.prototype.clone = function () {
  1625. return new Color3(this.r, this.g, this.b);
  1626. };
  1627. /**
  1628. * Copies the rgb values from the source in the current Color3
  1629. * @param source defines the source Color3 object
  1630. * @returns the updated Color3 object
  1631. */
  1632. Color3.prototype.copyFrom = function (source) {
  1633. this.r = source.r;
  1634. this.g = source.g;
  1635. this.b = source.b;
  1636. return this;
  1637. };
  1638. /**
  1639. * Updates the Color3 rgb values from the given floats
  1640. * @param r defines the red component to read from
  1641. * @param g defines the green component to read from
  1642. * @param b defines the blue component to read from
  1643. * @returns the current Color3 object
  1644. */
  1645. Color3.prototype.copyFromFloats = function (r, g, b) {
  1646. this.r = r;
  1647. this.g = g;
  1648. this.b = b;
  1649. return this;
  1650. };
  1651. /**
  1652. * Updates the Color3 rgb values from the given floats
  1653. * @param r defines the red component to read from
  1654. * @param g defines the green component to read from
  1655. * @param b defines the blue component to read from
  1656. * @returns the current Color3 object
  1657. */
  1658. Color3.prototype.set = function (r, g, b) {
  1659. return this.copyFromFloats(r, g, b);
  1660. };
  1661. /**
  1662. * Compute the Color3 hexadecimal code as a string
  1663. * @returns a string containing the hexadecimal representation of the Color3 object
  1664. */
  1665. Color3.prototype.toHexString = function () {
  1666. var intR = (this.r * 255) | 0;
  1667. var intG = (this.g * 255) | 0;
  1668. var intB = (this.b * 255) | 0;
  1669. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1670. };
  1671. /**
  1672. * Computes a new Color3 converted from the current one to linear space
  1673. * @returns a new Color3 object
  1674. */
  1675. Color3.prototype.toLinearSpace = function () {
  1676. var convertedColor = new Color3();
  1677. this.toLinearSpaceToRef(convertedColor);
  1678. return convertedColor;
  1679. };
  1680. /**
  1681. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1682. * @param convertedColor defines the Color3 object where to store the linear space version
  1683. * @returns the unmodified Color3
  1684. */
  1685. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1686. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1687. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1688. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1689. return this;
  1690. };
  1691. /**
  1692. * Computes a new Color3 converted from the current one to gamma space
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.prototype.toGammaSpace = function () {
  1696. var convertedColor = new Color3();
  1697. this.toGammaSpaceToRef(convertedColor);
  1698. return convertedColor;
  1699. };
  1700. /**
  1701. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1702. * @param convertedColor defines the Color3 object where to store the gamma space version
  1703. * @returns the unmodified Color3
  1704. */
  1705. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1706. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1707. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1708. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1709. return this;
  1710. };
  1711. // Statics
  1712. /**
  1713. * Creates a new Color3 from the string containing valid hexadecimal values
  1714. * @param hex defines a string containing valid hexadecimal values
  1715. * @returns a new Color3 object
  1716. */
  1717. Color3.FromHexString = function (hex) {
  1718. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1719. return new Color3(0, 0, 0);
  1720. }
  1721. var r = parseInt(hex.substring(1, 3), 16);
  1722. var g = parseInt(hex.substring(3, 5), 16);
  1723. var b = parseInt(hex.substring(5, 7), 16);
  1724. return Color3.FromInts(r, g, b);
  1725. };
  1726. /**
  1727. * Creates a new Vector3 from the starting index of the given array
  1728. * @param array defines the source array
  1729. * @param offset defines an offset in the source array
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.FromArray = function (array, offset) {
  1733. if (offset === void 0) { offset = 0; }
  1734. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1735. };
  1736. /**
  1737. * Creates a new Color3 from integer values (< 256)
  1738. * @param r defines the red component to read from (value between 0 and 255)
  1739. * @param g defines the green component to read from (value between 0 and 255)
  1740. * @param b defines the blue component to read from (value between 0 and 255)
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromInts = function (r, g, b) {
  1744. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1745. };
  1746. /**
  1747. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1748. * @param start defines the start Color3 value
  1749. * @param end defines the end Color3 value
  1750. * @param amount defines the gradient value between start and end
  1751. * @returns a new Color3 object
  1752. */
  1753. Color3.Lerp = function (start, end, amount) {
  1754. var r = start.r + ((end.r - start.r) * amount);
  1755. var g = start.g + ((end.g - start.g) * amount);
  1756. var b = start.b + ((end.b - start.b) * amount);
  1757. return new Color3(r, g, b);
  1758. };
  1759. /**
  1760. * Returns a Color3 value containing a red color
  1761. * @returns a new Color3 object
  1762. */
  1763. Color3.Red = function () { return new Color3(1, 0, 0); };
  1764. /**
  1765. * Returns a Color3 value containing a green color
  1766. * @returns a new Color3 object
  1767. */
  1768. Color3.Green = function () { return new Color3(0, 1, 0); };
  1769. /**
  1770. * Returns a Color3 value containing a blue color
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1774. /**
  1775. * Returns a Color3 value containing a black color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Black = function () { return new Color3(0, 0, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a white color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.White = function () { return new Color3(1, 1, 1); };
  1784. /**
  1785. * Returns a Color3 value containing a purple color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1789. /**
  1790. * Returns a Color3 value containing a magenta color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1794. /**
  1795. * Returns a Color3 value containing a yellow color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1799. /**
  1800. * Returns a Color3 value containing a gray color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1804. /**
  1805. * Returns a Color3 value containing a teal color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1809. /**
  1810. * Returns a Color3 value containing a random color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1814. return Color3;
  1815. }());
  1816. BABYLON.Color3 = Color3;
  1817. /**
  1818. * Class used to hold a RBGA color
  1819. */
  1820. var Color4 = /** @class */ (function () {
  1821. /**
  1822. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1823. * @param r defines the red component (between 0 and 1, default is 0)
  1824. * @param g defines the green component (between 0 and 1, default is 0)
  1825. * @param b defines the blue component (between 0 and 1, default is 0)
  1826. * @param a defines the alpha component (between 0 and 1, default is 1)
  1827. */
  1828. function Color4(
  1829. /**
  1830. * Defines the red component (between 0 and 1, default is 0)
  1831. */
  1832. r,
  1833. /**
  1834. * Defines the green component (between 0 and 1, default is 0)
  1835. */
  1836. g,
  1837. /**
  1838. * Defines the blue component (between 0 and 1, default is 0)
  1839. */
  1840. b,
  1841. /**
  1842. * Defines the alpha component (between 0 and 1, default is 1)
  1843. */
  1844. a) {
  1845. if (r === void 0) { r = 0; }
  1846. if (g === void 0) { g = 0; }
  1847. if (b === void 0) { b = 0; }
  1848. if (a === void 0) { a = 1; }
  1849. this.r = r;
  1850. this.g = g;
  1851. this.b = b;
  1852. this.a = a;
  1853. }
  1854. // Operators
  1855. /**
  1856. * Adds in place the given Color4 values to the current Color4 object
  1857. * @param right defines the second operand
  1858. * @returns the current updated Color4 object
  1859. */
  1860. Color4.prototype.addInPlace = function (right) {
  1861. this.r += right.r;
  1862. this.g += right.g;
  1863. this.b += right.b;
  1864. this.a += right.a;
  1865. return this;
  1866. };
  1867. /**
  1868. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1869. * @returns the new array
  1870. */
  1871. Color4.prototype.asArray = function () {
  1872. var result = new Array();
  1873. this.toArray(result, 0);
  1874. return result;
  1875. };
  1876. /**
  1877. * Stores from the starting index in the given array the Color4 successive values
  1878. * @param array defines the array where to store the r,g,b components
  1879. * @param index defines an optional index in the target array to define where to start storing values
  1880. * @returns the current Color4 object
  1881. */
  1882. Color4.prototype.toArray = function (array, index) {
  1883. if (index === undefined) {
  1884. index = 0;
  1885. }
  1886. array[index] = this.r;
  1887. array[index + 1] = this.g;
  1888. array[index + 2] = this.b;
  1889. array[index + 3] = this.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1894. * @param right defines the second operand
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.add = function (right) {
  1898. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1899. };
  1900. /**
  1901. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1902. * @param right defines the second operand
  1903. * @returns a new Color4 object
  1904. */
  1905. Color4.prototype.subtract = function (right) {
  1906. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1907. };
  1908. /**
  1909. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1910. * @param right defines the second operand
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the current Color4 object
  1913. */
  1914. Color4.prototype.subtractToRef = function (right, result) {
  1915. result.r = this.r - right.r;
  1916. result.g = this.g - right.g;
  1917. result.b = this.b - right.b;
  1918. result.a = this.a - right.a;
  1919. return this;
  1920. };
  1921. /**
  1922. * Creates a new Color4 with the current Color4 values multiplied by scale
  1923. * @param scale defines the scaling factor to apply
  1924. * @returns a new Color4 object
  1925. */
  1926. Color4.prototype.scale = function (scale) {
  1927. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1928. };
  1929. /**
  1930. * Multiplies the current Color4 values by scale and stores the result in "result"
  1931. * @param scale defines the scaling factor to apply
  1932. * @param result defines the Color4 object where to store the result
  1933. * @returns the current unmodified Color4
  1934. */
  1935. Color4.prototype.scaleToRef = function (scale, result) {
  1936. result.r = this.r * scale;
  1937. result.g = this.g * scale;
  1938. result.b = this.b * scale;
  1939. result.a = this.a * scale;
  1940. return this;
  1941. };
  1942. /**
  1943. * Scale the current Color4 values by a factor and add the result to a given Color4
  1944. * @param scale defines the scale factor
  1945. * @param result defines the Color4 object where to store the result
  1946. * @returns the unmodified current Color4
  1947. */
  1948. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1949. result.r += this.r * scale;
  1950. result.g += this.g * scale;
  1951. result.b += this.b * scale;
  1952. result.a += this.a * scale;
  1953. return this;
  1954. };
  1955. /**
  1956. * Clamps the rgb values by the min and max values and stores the result into "result"
  1957. * @param min defines minimum clamping value (default is 0)
  1958. * @param max defines maximum clamping value (default is 1)
  1959. * @param result defines color to store the result into.
  1960. * @returns the cuurent Color4
  1961. */
  1962. Color4.prototype.clampToRef = function (min, max, result) {
  1963. if (min === void 0) { min = 0; }
  1964. if (max === void 0) { max = 1; }
  1965. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1966. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1967. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1968. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1969. return this;
  1970. };
  1971. /**
  1972. * Multipy an Color4 value by another and return a new Color4 object
  1973. * @param color defines the Color4 value to multiply by
  1974. * @returns a new Color4 object
  1975. */
  1976. Color4.prototype.multiply = function (color) {
  1977. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1978. };
  1979. /**
  1980. * Multipy a Color4 value by another and push the result in a reference value
  1981. * @param color defines the Color4 value to multiply by
  1982. * @param result defines the Color4 to fill the result in
  1983. * @returns the result Color4
  1984. */
  1985. Color4.prototype.multiplyToRef = function (color, result) {
  1986. result.r = this.r * color.r;
  1987. result.g = this.g * color.g;
  1988. result.b = this.b * color.b;
  1989. result.a = this.a * color.a;
  1990. return result;
  1991. };
  1992. /**
  1993. * Creates a string with the Color4 current values
  1994. * @returns the string representation of the Color4 object
  1995. */
  1996. Color4.prototype.toString = function () {
  1997. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1998. };
  1999. /**
  2000. * Returns the string "Color4"
  2001. * @returns "Color4"
  2002. */
  2003. Color4.prototype.getClassName = function () {
  2004. return "Color4";
  2005. };
  2006. /**
  2007. * Compute the Color4 hash code
  2008. * @returns an unique number that can be used to hash Color4 objects
  2009. */
  2010. Color4.prototype.getHashCode = function () {
  2011. var hash = this.r || 0;
  2012. hash = (hash * 397) ^ (this.g || 0);
  2013. hash = (hash * 397) ^ (this.b || 0);
  2014. hash = (hash * 397) ^ (this.a || 0);
  2015. return hash;
  2016. };
  2017. /**
  2018. * Creates a new Color4 copied from the current one
  2019. * @returns a new Color4 object
  2020. */
  2021. Color4.prototype.clone = function () {
  2022. return new Color4(this.r, this.g, this.b, this.a);
  2023. };
  2024. /**
  2025. * Copies the given Color4 values into the current one
  2026. * @param source defines the source Color4 object
  2027. * @returns the current updated Color4 object
  2028. */
  2029. Color4.prototype.copyFrom = function (source) {
  2030. this.r = source.r;
  2031. this.g = source.g;
  2032. this.b = source.b;
  2033. this.a = source.a;
  2034. return this;
  2035. };
  2036. /**
  2037. * Copies the given float values into the current one
  2038. * @param r defines the red component to read from
  2039. * @param g defines the green component to read from
  2040. * @param b defines the blue component to read from
  2041. * @param a defines the alpha component to read from
  2042. * @returns the current updated Color4 object
  2043. */
  2044. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2045. this.r = r;
  2046. this.g = g;
  2047. this.b = b;
  2048. this.a = a;
  2049. return this;
  2050. };
  2051. /**
  2052. * Copies the given float values into the current one
  2053. * @param r defines the red component to read from
  2054. * @param g defines the green component to read from
  2055. * @param b defines the blue component to read from
  2056. * @param a defines the alpha component to read from
  2057. * @returns the current updated Color4 object
  2058. */
  2059. Color4.prototype.set = function (r, g, b, a) {
  2060. return this.copyFromFloats(r, g, b, a);
  2061. };
  2062. /**
  2063. * Compute the Color4 hexadecimal code as a string
  2064. * @returns a string containing the hexadecimal representation of the Color4 object
  2065. */
  2066. Color4.prototype.toHexString = function () {
  2067. var intR = (this.r * 255) | 0;
  2068. var intG = (this.g * 255) | 0;
  2069. var intB = (this.b * 255) | 0;
  2070. var intA = (this.a * 255) | 0;
  2071. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2072. };
  2073. /**
  2074. * Computes a new Color4 converted from the current one to linear space
  2075. * @returns a new Color4 object
  2076. */
  2077. Color4.prototype.toLinearSpace = function () {
  2078. var convertedColor = new Color4();
  2079. this.toLinearSpaceToRef(convertedColor);
  2080. return convertedColor;
  2081. };
  2082. /**
  2083. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2084. * @param convertedColor defines the Color4 object where to store the linear space version
  2085. * @returns the unmodified Color4
  2086. */
  2087. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2088. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2089. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2090. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2091. convertedColor.a = this.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Computes a new Color4 converted from the current one to gamma space
  2096. * @returns a new Color4 object
  2097. */
  2098. Color4.prototype.toGammaSpace = function () {
  2099. var convertedColor = new Color4();
  2100. this.toGammaSpaceToRef(convertedColor);
  2101. return convertedColor;
  2102. };
  2103. /**
  2104. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2105. * @param convertedColor defines the Color4 object where to store the gamma space version
  2106. * @returns the unmodified Color4
  2107. */
  2108. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2109. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2110. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2111. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2112. convertedColor.a = this.a;
  2113. return this;
  2114. };
  2115. // Statics
  2116. /**
  2117. * Creates a new Color4 from the string containing valid hexadecimal values
  2118. * @param hex defines a string containing valid hexadecimal values
  2119. * @returns a new Color4 object
  2120. */
  2121. Color4.FromHexString = function (hex) {
  2122. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2123. return new Color4(0.0, 0.0, 0.0, 0.0);
  2124. }
  2125. var r = parseInt(hex.substring(1, 3), 16);
  2126. var g = parseInt(hex.substring(3, 5), 16);
  2127. var b = parseInt(hex.substring(5, 7), 16);
  2128. var a = parseInt(hex.substring(7, 9), 16);
  2129. return Color4.FromInts(r, g, b, a);
  2130. };
  2131. /**
  2132. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2133. * @param left defines the start value
  2134. * @param right defines the end value
  2135. * @param amount defines the gradient factor
  2136. * @returns a new Color4 object
  2137. */
  2138. Color4.Lerp = function (left, right, amount) {
  2139. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2140. Color4.LerpToRef(left, right, amount, result);
  2141. return result;
  2142. };
  2143. /**
  2144. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2145. * @param left defines the start value
  2146. * @param right defines the end value
  2147. * @param amount defines the gradient factor
  2148. * @param result defines the Color4 object where to store data
  2149. */
  2150. Color4.LerpToRef = function (left, right, amount, result) {
  2151. result.r = left.r + (right.r - left.r) * amount;
  2152. result.g = left.g + (right.g - left.g) * amount;
  2153. result.b = left.b + (right.b - left.b) * amount;
  2154. result.a = left.a + (right.a - left.a) * amount;
  2155. };
  2156. /**
  2157. * Creates a new Color4 from the starting index element of the given array
  2158. * @param array defines the source array to read from
  2159. * @param offset defines the offset in the source array
  2160. * @returns a new Color4 object
  2161. */
  2162. Color4.FromArray = function (array, offset) {
  2163. if (offset === void 0) { offset = 0; }
  2164. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2165. };
  2166. /**
  2167. * Creates a new Color3 from integer values (< 256)
  2168. * @param r defines the red component to read from (value between 0 and 255)
  2169. * @param g defines the green component to read from (value between 0 and 255)
  2170. * @param b defines the blue component to read from (value between 0 and 255)
  2171. * @param a defines the alpha component to read from (value between 0 and 255)
  2172. * @returns a new Color3 object
  2173. */
  2174. Color4.FromInts = function (r, g, b, a) {
  2175. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2176. };
  2177. /**
  2178. * Check the content of a given array and convert it to an array containing RGBA data
  2179. * If the original array was already containing count * 4 values then it is returned directly
  2180. * @param colors defines the array to check
  2181. * @param count defines the number of RGBA data to expect
  2182. * @returns an array containing count * 4 values (RGBA)
  2183. */
  2184. Color4.CheckColors4 = function (colors, count) {
  2185. // Check if color3 was used
  2186. if (colors.length === count * 3) {
  2187. var colors4 = [];
  2188. for (var index = 0; index < colors.length; index += 3) {
  2189. var newIndex = (index / 3) * 4;
  2190. colors4[newIndex] = colors[index];
  2191. colors4[newIndex + 1] = colors[index + 1];
  2192. colors4[newIndex + 2] = colors[index + 2];
  2193. colors4[newIndex + 3] = 1.0;
  2194. }
  2195. return colors4;
  2196. }
  2197. return colors;
  2198. };
  2199. return Color4;
  2200. }());
  2201. BABYLON.Color4 = Color4;
  2202. /**
  2203. * Class representing a vector containing 2 coordinates
  2204. */
  2205. var Vector2 = /** @class */ (function () {
  2206. /**
  2207. * Creates a new Vector2 from the given x and y coordinates
  2208. * @param x defines the first coordinate
  2209. * @param y defines the second coordinate
  2210. */
  2211. function Vector2(
  2212. /** defines the first coordinate */
  2213. x,
  2214. /** defines the second coordinate */
  2215. y) {
  2216. this.x = x;
  2217. this.y = y;
  2218. }
  2219. /**
  2220. * Gets a string with the Vector2 coordinates
  2221. * @returns a string with the Vector2 coordinates
  2222. */
  2223. Vector2.prototype.toString = function () {
  2224. return "{X: " + this.x + " Y:" + this.y + "}";
  2225. };
  2226. /**
  2227. * Gets class name
  2228. * @returns the string "Vector2"
  2229. */
  2230. Vector2.prototype.getClassName = function () {
  2231. return "Vector2";
  2232. };
  2233. /**
  2234. * Gets current vector hash code
  2235. * @returns the Vector2 hash code as a number
  2236. */
  2237. Vector2.prototype.getHashCode = function () {
  2238. var hash = this.x || 0;
  2239. hash = (hash * 397) ^ (this.y || 0);
  2240. return hash;
  2241. };
  2242. // Operators
  2243. /**
  2244. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2245. * @param array defines the source array
  2246. * @param index defines the offset in source array
  2247. * @returns the current Vector2
  2248. */
  2249. Vector2.prototype.toArray = function (array, index) {
  2250. if (index === void 0) { index = 0; }
  2251. array[index] = this.x;
  2252. array[index + 1] = this.y;
  2253. return this;
  2254. };
  2255. /**
  2256. * Copy the current vector to an array
  2257. * @returns a new array with 2 elements: the Vector2 coordinates.
  2258. */
  2259. Vector2.prototype.asArray = function () {
  2260. var result = new Array();
  2261. this.toArray(result, 0);
  2262. return result;
  2263. };
  2264. /**
  2265. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2266. * @param source defines the source Vector2
  2267. * @returns the current updated Vector2
  2268. */
  2269. Vector2.prototype.copyFrom = function (source) {
  2270. this.x = source.x;
  2271. this.y = source.y;
  2272. return this;
  2273. };
  2274. /**
  2275. * Sets the Vector2 coordinates with the given floats
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. * @returns the current updated Vector2
  2279. */
  2280. Vector2.prototype.copyFromFloats = function (x, y) {
  2281. this.x = x;
  2282. this.y = y;
  2283. return this;
  2284. };
  2285. /**
  2286. * Sets the Vector2 coordinates with the given floats
  2287. * @param x defines the first coordinate
  2288. * @param y defines the second coordinate
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.set = function (x, y) {
  2292. return this.copyFromFloats(x, y);
  2293. };
  2294. /**
  2295. * Add another vector with the current one
  2296. * @param otherVector defines the other vector
  2297. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2298. */
  2299. Vector2.prototype.add = function (otherVector) {
  2300. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2301. };
  2302. /**
  2303. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2304. * @param otherVector defines the other vector
  2305. * @param result defines the target vector
  2306. * @returns the unmodified current Vector2
  2307. */
  2308. Vector2.prototype.addToRef = function (otherVector, result) {
  2309. result.x = this.x + otherVector.x;
  2310. result.y = this.y + otherVector.y;
  2311. return this;
  2312. };
  2313. /**
  2314. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2315. * @param otherVector defines the other vector
  2316. * @returns the current updated Vector2
  2317. */
  2318. Vector2.prototype.addInPlace = function (otherVector) {
  2319. this.x += otherVector.x;
  2320. this.y += otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2325. * @param otherVector defines the other vector
  2326. * @returns a new Vector2
  2327. */
  2328. Vector2.prototype.addVector3 = function (otherVector) {
  2329. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2330. };
  2331. /**
  2332. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2333. * @param otherVector defines the other vector
  2334. * @returns a new Vector2
  2335. */
  2336. Vector2.prototype.subtract = function (otherVector) {
  2337. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2338. };
  2339. /**
  2340. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2341. * @param otherVector defines the other vector
  2342. * @param result defines the target vector
  2343. * @returns the unmodified current Vector2
  2344. */
  2345. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2346. result.x = this.x - otherVector.x;
  2347. result.y = this.y - otherVector.y;
  2348. return this;
  2349. };
  2350. /**
  2351. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2352. * @param otherVector defines the other vector
  2353. * @returns the current updated Vector2
  2354. */
  2355. Vector2.prototype.subtractInPlace = function (otherVector) {
  2356. this.x -= otherVector.x;
  2357. this.y -= otherVector.y;
  2358. return this;
  2359. };
  2360. /**
  2361. * Multiplies in place the current Vector2 coordinates by the given ones
  2362. * @param otherVector defines the other vector
  2363. * @returns the current updated Vector2
  2364. */
  2365. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2366. this.x *= otherVector.x;
  2367. this.y *= otherVector.y;
  2368. return this;
  2369. };
  2370. /**
  2371. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2372. * @param otherVector defines the other vector
  2373. * @returns a new Vector2
  2374. */
  2375. Vector2.prototype.multiply = function (otherVector) {
  2376. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2377. };
  2378. /**
  2379. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2380. * @param otherVector defines the other vector
  2381. * @param result defines the target vector
  2382. * @returns the unmodified current Vector2
  2383. */
  2384. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2385. result.x = this.x * otherVector.x;
  2386. result.y = this.y * otherVector.y;
  2387. return this;
  2388. };
  2389. /**
  2390. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2391. * @param x defines the first coordinate
  2392. * @param y defines the second coordinate
  2393. * @returns a new Vector2
  2394. */
  2395. Vector2.prototype.multiplyByFloats = function (x, y) {
  2396. return new Vector2(this.x * x, this.y * y);
  2397. };
  2398. /**
  2399. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.divide = function (otherVector) {
  2404. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2405. };
  2406. /**
  2407. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2408. * @param otherVector defines the other vector
  2409. * @param result defines the target vector
  2410. * @returns the unmodified current Vector2
  2411. */
  2412. Vector2.prototype.divideToRef = function (otherVector, result) {
  2413. result.x = this.x / otherVector.x;
  2414. result.y = this.y / otherVector.y;
  2415. return this;
  2416. };
  2417. /**
  2418. * Divides the current Vector3 coordinates by the given ones
  2419. * @param otherVector defines the other vector
  2420. * @returns the current updated Vector2
  2421. */
  2422. Vector2.prototype.divideInPlace = function (otherVector) {
  2423. return this.divideToRef(otherVector, this);
  2424. };
  2425. /**
  2426. * Gets a new Vector2 with current Vector2 negated coordinates
  2427. * @returns a new Vector2
  2428. */
  2429. Vector2.prototype.negate = function () {
  2430. return new Vector2(-this.x, -this.y);
  2431. };
  2432. /**
  2433. * Multiply the Vector2 coordinates by scale
  2434. * @param scale defines the scaling factor
  2435. * @returns the current updated Vector2
  2436. */
  2437. Vector2.prototype.scaleInPlace = function (scale) {
  2438. this.x *= scale;
  2439. this.y *= scale;
  2440. return this;
  2441. };
  2442. /**
  2443. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2444. * @param scale defines the scaling factor
  2445. * @returns a new Vector2
  2446. */
  2447. Vector2.prototype.scale = function (scale) {
  2448. var result = new Vector2(0, 0);
  2449. this.scaleToRef(scale, result);
  2450. return result;
  2451. };
  2452. /**
  2453. * Scale the current Vector2 values by a factor to a given Vector2
  2454. * @param scale defines the scale factor
  2455. * @param result defines the Vector2 object where to store the result
  2456. * @returns the unmodified current Vector2
  2457. */
  2458. Vector2.prototype.scaleToRef = function (scale, result) {
  2459. result.x = this.x * scale;
  2460. result.y = this.y * scale;
  2461. return this;
  2462. };
  2463. /**
  2464. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2465. * @param scale defines the scale factor
  2466. * @param result defines the Vector2 object where to store the result
  2467. * @returns the unmodified current Vector2
  2468. */
  2469. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2470. result.x += this.x * scale;
  2471. result.y += this.y * scale;
  2472. return this;
  2473. };
  2474. /**
  2475. * Gets a boolean if two vectors are equals
  2476. * @param otherVector defines the other vector
  2477. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2478. */
  2479. Vector2.prototype.equals = function (otherVector) {
  2480. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2481. };
  2482. /**
  2483. * Gets a boolean if two vectors are equals (using an epsilon value)
  2484. * @param otherVector defines the other vector
  2485. * @param epsilon defines the minimal distance to consider equality
  2486. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2487. */
  2488. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2489. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2490. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2491. };
  2492. // Properties
  2493. /**
  2494. * Gets the length of the vector
  2495. * @returns the vector length (float)
  2496. */
  2497. Vector2.prototype.length = function () {
  2498. return Math.sqrt(this.x * this.x + this.y * this.y);
  2499. };
  2500. /**
  2501. * Gets the vector squared length
  2502. * @returns the vector squared length (float)
  2503. */
  2504. Vector2.prototype.lengthSquared = function () {
  2505. return (this.x * this.x + this.y * this.y);
  2506. };
  2507. // Methods
  2508. /**
  2509. * Normalize the vector
  2510. * @returns the current updated Vector2
  2511. */
  2512. Vector2.prototype.normalize = function () {
  2513. var len = this.length();
  2514. if (len === 0)
  2515. return this;
  2516. var num = 1.0 / len;
  2517. this.x *= num;
  2518. this.y *= num;
  2519. return this;
  2520. };
  2521. /**
  2522. * Gets a new Vector2 copied from the Vector2
  2523. * @returns a new Vector2
  2524. */
  2525. Vector2.prototype.clone = function () {
  2526. return new Vector2(this.x, this.y);
  2527. };
  2528. // Statics
  2529. /**
  2530. * Gets a new Vector2(0, 0)
  2531. * @returns a new Vector2
  2532. */
  2533. Vector2.Zero = function () {
  2534. return new Vector2(0, 0);
  2535. };
  2536. /**
  2537. * Gets a new Vector2(1, 1)
  2538. * @returns a new Vector2
  2539. */
  2540. Vector2.One = function () {
  2541. return new Vector2(1, 1);
  2542. };
  2543. /**
  2544. * Gets a new Vector2 set from the given index element of the given array
  2545. * @param array defines the data source
  2546. * @param offset defines the offset in the data source
  2547. * @returns a new Vector2
  2548. */
  2549. Vector2.FromArray = function (array, offset) {
  2550. if (offset === void 0) { offset = 0; }
  2551. return new Vector2(array[offset], array[offset + 1]);
  2552. };
  2553. /**
  2554. * Sets "result" from the given index element of the given array
  2555. * @param array defines the data source
  2556. * @param offset defines the offset in the data source
  2557. * @param result defines the target vector
  2558. */
  2559. Vector2.FromArrayToRef = function (array, offset, result) {
  2560. result.x = array[offset];
  2561. result.y = array[offset + 1];
  2562. };
  2563. /**
  2564. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2565. * @param value1 defines 1st point of control
  2566. * @param value2 defines 2nd point of control
  2567. * @param value3 defines 3rd point of control
  2568. * @param value4 defines 4th point of control
  2569. * @param amount defines the interpolation factor
  2570. * @returns a new Vector2
  2571. */
  2572. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2573. var squared = amount * amount;
  2574. var cubed = amount * squared;
  2575. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2576. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2577. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2578. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2579. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2580. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2581. return new Vector2(x, y);
  2582. };
  2583. /**
  2584. * 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".
  2585. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2586. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2587. * @param value defines the value to clamp
  2588. * @param min defines the lower limit
  2589. * @param max defines the upper limit
  2590. * @returns a new Vector2
  2591. */
  2592. Vector2.Clamp = function (value, min, max) {
  2593. var x = value.x;
  2594. x = (x > max.x) ? max.x : x;
  2595. x = (x < min.x) ? min.x : x;
  2596. var y = value.y;
  2597. y = (y > max.y) ? max.y : y;
  2598. y = (y < min.y) ? min.y : y;
  2599. return new Vector2(x, y);
  2600. };
  2601. /**
  2602. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2603. * @param value1 defines the 1st control point
  2604. * @param tangent1 defines the outgoing tangent
  2605. * @param value2 defines the 2nd control point
  2606. * @param tangent2 defines the incoming tangent
  2607. * @param amount defines the interpolation factor
  2608. * @returns a new Vector2
  2609. */
  2610. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2611. var squared = amount * amount;
  2612. var cubed = amount * squared;
  2613. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2614. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2615. var part3 = (cubed - (2.0 * squared)) + amount;
  2616. var part4 = cubed - squared;
  2617. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2618. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2619. return new Vector2(x, y);
  2620. };
  2621. /**
  2622. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2623. * @param start defines the start vector
  2624. * @param end defines the end vector
  2625. * @param amount defines the interpolation factor
  2626. * @returns a new Vector2
  2627. */
  2628. Vector2.Lerp = function (start, end, amount) {
  2629. var x = start.x + ((end.x - start.x) * amount);
  2630. var y = start.y + ((end.y - start.y) * amount);
  2631. return new Vector2(x, y);
  2632. };
  2633. /**
  2634. * Gets the dot product of the vector "left" and the vector "right"
  2635. * @param left defines first vector
  2636. * @param right defines second vector
  2637. * @returns the dot product (float)
  2638. */
  2639. Vector2.Dot = function (left, right) {
  2640. return left.x * right.x + left.y * right.y;
  2641. };
  2642. /**
  2643. * Returns a new Vector2 equal to the normalized given vector
  2644. * @param vector defines the vector to normalize
  2645. * @returns a new Vector2
  2646. */
  2647. Vector2.Normalize = function (vector) {
  2648. var newVector = vector.clone();
  2649. newVector.normalize();
  2650. return newVector;
  2651. };
  2652. /**
  2653. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2654. * @param left defines 1st vector
  2655. * @param right defines 2nd vector
  2656. * @returns a new Vector2
  2657. */
  2658. Vector2.Minimize = function (left, right) {
  2659. var x = (left.x < right.x) ? left.x : right.x;
  2660. var y = (left.y < right.y) ? left.y : right.y;
  2661. return new Vector2(x, y);
  2662. };
  2663. /**
  2664. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2665. * @param left defines 1st vector
  2666. * @param right defines 2nd vector
  2667. * @returns a new Vector2
  2668. */
  2669. Vector2.Maximize = function (left, right) {
  2670. var x = (left.x > right.x) ? left.x : right.x;
  2671. var y = (left.y > right.y) ? left.y : right.y;
  2672. return new Vector2(x, y);
  2673. };
  2674. /**
  2675. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2676. * @param vector defines the vector to transform
  2677. * @param transformation defines the matrix to apply
  2678. * @returns a new Vector2
  2679. */
  2680. Vector2.Transform = function (vector, transformation) {
  2681. var r = Vector2.Zero();
  2682. Vector2.TransformToRef(vector, transformation, r);
  2683. return r;
  2684. };
  2685. /**
  2686. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2687. * @param vector defines the vector to transform
  2688. * @param transformation defines the matrix to apply
  2689. * @param result defines the target vector
  2690. */
  2691. Vector2.TransformToRef = function (vector, transformation, result) {
  2692. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2693. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2694. result.x = x;
  2695. result.y = y;
  2696. };
  2697. /**
  2698. * Determines if a given vector is included in a triangle
  2699. * @param p defines the vector to test
  2700. * @param p0 defines 1st triangle point
  2701. * @param p1 defines 2nd triangle point
  2702. * @param p2 defines 3rd triangle point
  2703. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2704. */
  2705. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2706. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2707. var sign = a < 0 ? -1 : 1;
  2708. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2709. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2710. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2711. };
  2712. /**
  2713. * Gets the distance between the vectors "value1" and "value2"
  2714. * @param value1 defines first vector
  2715. * @param value2 defines second vector
  2716. * @returns the distance between vectors
  2717. */
  2718. Vector2.Distance = function (value1, value2) {
  2719. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2720. };
  2721. /**
  2722. * Returns the squared distance between the vectors "value1" and "value2"
  2723. * @param value1 defines first vector
  2724. * @param value2 defines second vector
  2725. * @returns the squared distance between vectors
  2726. */
  2727. Vector2.DistanceSquared = function (value1, value2) {
  2728. var x = value1.x - value2.x;
  2729. var y = value1.y - value2.y;
  2730. return (x * x) + (y * y);
  2731. };
  2732. /**
  2733. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2734. * @param value1 defines first vector
  2735. * @param value2 defines second vector
  2736. * @returns a new Vector2
  2737. */
  2738. Vector2.Center = function (value1, value2) {
  2739. var center = value1.add(value2);
  2740. center.scaleInPlace(0.5);
  2741. return center;
  2742. };
  2743. /**
  2744. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2745. * @param p defines the middle point
  2746. * @param segA defines one point of the segment
  2747. * @param segB defines the other point of the segment
  2748. * @returns the shortest distance
  2749. */
  2750. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2751. var l2 = Vector2.DistanceSquared(segA, segB);
  2752. if (l2 === 0.0) {
  2753. return Vector2.Distance(p, segA);
  2754. }
  2755. var v = segB.subtract(segA);
  2756. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2757. var proj = segA.add(v.multiplyByFloats(t, t));
  2758. return Vector2.Distance(p, proj);
  2759. };
  2760. return Vector2;
  2761. }());
  2762. BABYLON.Vector2 = Vector2;
  2763. /**
  2764. * Classed used to store (x,y,z) vector representation
  2765. * A Vector3 is the main object used in 3D geometry
  2766. * It can represent etiher the coordinates of a point the space, either a direction
  2767. * Reminder: Babylon.js uses a left handed forward facing system
  2768. */
  2769. var Vector3 = /** @class */ (function () {
  2770. /**
  2771. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2772. * @param x defines the first coordinates (on X axis)
  2773. * @param y defines the second coordinates (on Y axis)
  2774. * @param z defines the third coordinates (on Z axis)
  2775. */
  2776. function Vector3(
  2777. /**
  2778. * Defines the first coordinates (on X axis)
  2779. */
  2780. x,
  2781. /**
  2782. * Defines the second coordinates (on Y axis)
  2783. */
  2784. y,
  2785. /**
  2786. * Defines the third coordinates (on Z axis)
  2787. */
  2788. z) {
  2789. this.x = x;
  2790. this.y = y;
  2791. this.z = z;
  2792. }
  2793. /**
  2794. * Creates a string representation of the Vector3
  2795. * @returns a string with the Vector3 coordinates.
  2796. */
  2797. Vector3.prototype.toString = function () {
  2798. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2799. };
  2800. /**
  2801. * Gets the class name
  2802. * @returns the string "Vector3"
  2803. */
  2804. Vector3.prototype.getClassName = function () {
  2805. return "Vector3";
  2806. };
  2807. /**
  2808. * Creates the Vector3 hash code
  2809. * @returns a number which tends to be unique between Vector3 instances
  2810. */
  2811. Vector3.prototype.getHashCode = function () {
  2812. var hash = this.x || 0;
  2813. hash = (hash * 397) ^ (this.y || 0);
  2814. hash = (hash * 397) ^ (this.z || 0);
  2815. return hash;
  2816. };
  2817. // Operators
  2818. /**
  2819. * Creates an array containing three elements : the coordinates of the Vector3
  2820. * @returns a new array of numbers
  2821. */
  2822. Vector3.prototype.asArray = function () {
  2823. var result = [];
  2824. this.toArray(result, 0);
  2825. return result;
  2826. };
  2827. /**
  2828. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2829. * @param array defines the destination array
  2830. * @param index defines the offset in the destination array
  2831. * @returns the current Vector3
  2832. */
  2833. Vector3.prototype.toArray = function (array, index) {
  2834. if (index === void 0) { index = 0; }
  2835. array[index] = this.x;
  2836. array[index + 1] = this.y;
  2837. array[index + 2] = this.z;
  2838. return this;
  2839. };
  2840. /**
  2841. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2842. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2843. */
  2844. Vector3.prototype.toQuaternion = function () {
  2845. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2846. };
  2847. /**
  2848. * Adds the given vector to the current Vector3
  2849. * @param otherVector defines the second operand
  2850. * @returns the current updated Vector3
  2851. */
  2852. Vector3.prototype.addInPlace = function (otherVector) {
  2853. this.x += otherVector.x;
  2854. this.y += otherVector.y;
  2855. this.z += otherVector.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2860. * @param otherVector defines the second operand
  2861. * @returns the resulting Vector3
  2862. */
  2863. Vector3.prototype.add = function (otherVector) {
  2864. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2865. };
  2866. /**
  2867. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2868. * @param otherVector defines the second operand
  2869. * @param result defines the Vector3 object where to store the result
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.addToRef = function (otherVector, result) {
  2873. result.x = this.x + otherVector.x;
  2874. result.y = this.y + otherVector.y;
  2875. result.z = this.z + otherVector.z;
  2876. return this;
  2877. };
  2878. /**
  2879. * Subtract the given vector from the current Vector3
  2880. * @param otherVector defines the second operand
  2881. * @returns the current updated Vector3
  2882. */
  2883. Vector3.prototype.subtractInPlace = function (otherVector) {
  2884. this.x -= otherVector.x;
  2885. this.y -= otherVector.y;
  2886. this.z -= otherVector.z;
  2887. return this;
  2888. };
  2889. /**
  2890. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2891. * @param otherVector defines the second operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtract = function (otherVector) {
  2895. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2896. };
  2897. /**
  2898. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2899. * @param otherVector defines the second operand
  2900. * @param result defines the Vector3 object where to store the result
  2901. * @returns the current Vector3
  2902. */
  2903. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2904. result.x = this.x - otherVector.x;
  2905. result.y = this.y - otherVector.y;
  2906. result.z = this.z - otherVector.z;
  2907. return this;
  2908. };
  2909. /**
  2910. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2911. * @param x defines the x coordinate of the operand
  2912. * @param y defines the y coordinate of the operand
  2913. * @param z defines the z coordinate of the operand
  2914. * @returns the resulting Vector3
  2915. */
  2916. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2917. return new Vector3(this.x - x, this.y - y, this.z - z);
  2918. };
  2919. /**
  2920. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2921. * @param x defines the x coordinate of the operand
  2922. * @param y defines the y coordinate of the operand
  2923. * @param z defines the z coordinate of the operand
  2924. * @param result defines the Vector3 object where to store the result
  2925. * @returns the current Vector3
  2926. */
  2927. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2928. result.x = this.x - x;
  2929. result.y = this.y - y;
  2930. result.z = this.z - z;
  2931. return this;
  2932. };
  2933. /**
  2934. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2935. * @returns a new Vector3
  2936. */
  2937. Vector3.prototype.negate = function () {
  2938. return new Vector3(-this.x, -this.y, -this.z);
  2939. };
  2940. /**
  2941. * Multiplies the Vector3 coordinates by the float "scale"
  2942. * @param scale defines the multiplier factor
  2943. * @returns the current updated Vector3
  2944. */
  2945. Vector3.prototype.scaleInPlace = function (scale) {
  2946. this.x *= scale;
  2947. this.y *= scale;
  2948. this.z *= scale;
  2949. return this;
  2950. };
  2951. /**
  2952. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2953. * @param scale defines the multiplier factor
  2954. * @returns a new Vector3
  2955. */
  2956. Vector3.prototype.scale = function (scale) {
  2957. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2958. };
  2959. /**
  2960. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2961. * @param scale defines the multiplier factor
  2962. * @param result defines the Vector3 object where to store the result
  2963. * @returns the current Vector3
  2964. */
  2965. Vector3.prototype.scaleToRef = function (scale, result) {
  2966. result.x = this.x * scale;
  2967. result.y = this.y * scale;
  2968. result.z = this.z * scale;
  2969. return this;
  2970. };
  2971. /**
  2972. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2973. * @param scale defines the scale factor
  2974. * @param result defines the Vector3 object where to store the result
  2975. * @returns the unmodified current Vector3
  2976. */
  2977. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2978. result.x += this.x * scale;
  2979. result.y += this.y * scale;
  2980. result.z += this.z * scale;
  2981. return this;
  2982. };
  2983. /**
  2984. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2985. * @param otherVector defines the second operand
  2986. * @returns true if both vectors are equals
  2987. */
  2988. Vector3.prototype.equals = function (otherVector) {
  2989. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2990. };
  2991. /**
  2992. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2993. * @param otherVector defines the second operand
  2994. * @param epsilon defines the minimal distance to define values as equals
  2995. * @returns true if both vectors are distant less than epsilon
  2996. */
  2997. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2998. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2999. 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);
  3000. };
  3001. /**
  3002. * Returns true if the current Vector3 coordinates equals the given floats
  3003. * @param x defines the x coordinate of the operand
  3004. * @param y defines the y coordinate of the operand
  3005. * @param z defines the z coordinate of the operand
  3006. * @returns true if both vectors are equals
  3007. */
  3008. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3009. return this.x === x && this.y === y && this.z === z;
  3010. };
  3011. /**
  3012. * Multiplies the current Vector3 coordinates by the given ones
  3013. * @param otherVector defines the second operand
  3014. * @returns the current updated Vector3
  3015. */
  3016. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3017. this.x *= otherVector.x;
  3018. this.y *= otherVector.y;
  3019. this.z *= otherVector.z;
  3020. return this;
  3021. };
  3022. /**
  3023. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3024. * @param otherVector defines the second operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiply = function (otherVector) {
  3028. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3029. };
  3030. /**
  3031. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3032. * @param otherVector defines the second operand
  3033. * @param result defines the Vector3 object where to store the result
  3034. * @returns the current Vector3
  3035. */
  3036. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3037. result.x = this.x * otherVector.x;
  3038. result.y = this.y * otherVector.y;
  3039. result.z = this.z * otherVector.z;
  3040. return this;
  3041. };
  3042. /**
  3043. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3044. * @param x defines the x coordinate of the operand
  3045. * @param y defines the y coordinate of the operand
  3046. * @param z defines the z coordinate of the operand
  3047. * @returns the new Vector3
  3048. */
  3049. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3050. return new Vector3(this.x * x, this.y * y, this.z * z);
  3051. };
  3052. /**
  3053. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3054. * @param otherVector defines the second operand
  3055. * @returns the new Vector3
  3056. */
  3057. Vector3.prototype.divide = function (otherVector) {
  3058. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3059. };
  3060. /**
  3061. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3062. * @param otherVector defines the second operand
  3063. * @param result defines the Vector3 object where to store the result
  3064. * @returns the current Vector3
  3065. */
  3066. Vector3.prototype.divideToRef = function (otherVector, result) {
  3067. result.x = this.x / otherVector.x;
  3068. result.y = this.y / otherVector.y;
  3069. result.z = this.z / otherVector.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Divides the current Vector3 coordinates by the given ones.
  3074. * @param otherVector defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.divideInPlace = function (otherVector) {
  3078. return this.divideToRef(otherVector, this);
  3079. };
  3080. /**
  3081. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3082. * @param other defines the second operand
  3083. * @returns the current updated Vector3
  3084. */
  3085. Vector3.prototype.minimizeInPlace = function (other) {
  3086. if (other.x < this.x)
  3087. this.x = other.x;
  3088. if (other.y < this.y)
  3089. this.y = other.y;
  3090. if (other.z < this.z)
  3091. this.z = other.z;
  3092. return this;
  3093. };
  3094. /**
  3095. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3096. * @param other defines the second operand
  3097. * @returns the current updated Vector3
  3098. */
  3099. Vector3.prototype.maximizeInPlace = function (other) {
  3100. if (other.x > this.x)
  3101. this.x = other.x;
  3102. if (other.y > this.y)
  3103. this.y = other.y;
  3104. if (other.z > this.z)
  3105. this.z = other.z;
  3106. return this;
  3107. };
  3108. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3109. /**
  3110. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3111. */
  3112. get: function () {
  3113. var absX = Math.abs(this.x);
  3114. var absY = Math.abs(this.y);
  3115. if (absX !== absY) {
  3116. return true;
  3117. }
  3118. var absZ = Math.abs(this.z);
  3119. if (absX !== absZ) {
  3120. return true;
  3121. }
  3122. if (absY !== absZ) {
  3123. return true;
  3124. }
  3125. return false;
  3126. },
  3127. enumerable: true,
  3128. configurable: true
  3129. });
  3130. // Properties
  3131. /**
  3132. * Gets the length of the Vector3
  3133. * @returns the length of the Vecto3
  3134. */
  3135. Vector3.prototype.length = function () {
  3136. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3137. };
  3138. /**
  3139. * Gets the squared length of the Vector3
  3140. * @returns squared length of the Vector3
  3141. */
  3142. Vector3.prototype.lengthSquared = function () {
  3143. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3144. };
  3145. /**
  3146. * Normalize the current Vector3.
  3147. * Please note that this is an in place operation.
  3148. * @returns the current updated Vector3
  3149. */
  3150. Vector3.prototype.normalize = function () {
  3151. var len = this.length();
  3152. if (len === 0 || len === 1.0)
  3153. return this;
  3154. var num = 1.0 / len;
  3155. this.x *= num;
  3156. this.y *= num;
  3157. this.z *= num;
  3158. return this;
  3159. };
  3160. /**
  3161. * Normalize the current Vector3 to a new vector
  3162. * @returns the new Vector3
  3163. */
  3164. Vector3.prototype.normalizeToNew = function () {
  3165. var normalized = new Vector3(0, 0, 0);
  3166. this.normalizeToRef(normalized);
  3167. return normalized;
  3168. };
  3169. /**
  3170. * Normalize the current Vector3 to the reference
  3171. * @param reference define the Vector3 to update
  3172. * @returns the updated Vector3
  3173. */
  3174. Vector3.prototype.normalizeToRef = function (reference) {
  3175. var len = this.length();
  3176. if (len === 0 || len === 1.0) {
  3177. reference.set(this.x, this.y, this.z);
  3178. return reference;
  3179. }
  3180. var scale = 1.0 / len;
  3181. this.scaleToRef(scale, reference);
  3182. return reference;
  3183. };
  3184. /**
  3185. * Creates a new Vector3 copied from the current Vector3
  3186. * @returns the new Vector3
  3187. */
  3188. Vector3.prototype.clone = function () {
  3189. return new Vector3(this.x, this.y, this.z);
  3190. };
  3191. /**
  3192. * Copies the given vector coordinates to the current Vector3 ones
  3193. * @param source defines the source Vector3
  3194. * @returns the current updated Vector3
  3195. */
  3196. Vector3.prototype.copyFrom = function (source) {
  3197. this.x = source.x;
  3198. this.y = source.y;
  3199. this.z = source.z;
  3200. return this;
  3201. };
  3202. /**
  3203. * Copies the given floats to the current Vector3 coordinates
  3204. * @param x defines the x coordinate of the operand
  3205. * @param y defines the y coordinate of the operand
  3206. * @param z defines the z coordinate of the operand
  3207. * @returns the current updated Vector3
  3208. */
  3209. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3210. this.x = x;
  3211. this.y = y;
  3212. this.z = z;
  3213. return this;
  3214. };
  3215. /**
  3216. * Copies the given floats to the current Vector3 coordinates
  3217. * @param x defines the x coordinate of the operand
  3218. * @param y defines the y coordinate of the operand
  3219. * @param z defines the z coordinate of the operand
  3220. * @returns the current updated Vector3
  3221. */
  3222. Vector3.prototype.set = function (x, y, z) {
  3223. return this.copyFromFloats(x, y, z);
  3224. };
  3225. // Statics
  3226. /**
  3227. * Get the clip factor between two vectors
  3228. * @param vector0 defines the first operand
  3229. * @param vector1 defines the second operand
  3230. * @param axis defines the axis to use
  3231. * @param size defines the size along the axis
  3232. * @returns the clip factor
  3233. */
  3234. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3235. var d0 = Vector3.Dot(vector0, axis) - size;
  3236. var d1 = Vector3.Dot(vector1, axis) - size;
  3237. var s = d0 / (d0 - d1);
  3238. return s;
  3239. };
  3240. /**
  3241. * Get angle between two vectors
  3242. * @param vector0 angle between vector0 and vector1
  3243. * @param vector1 angle between vector0 and vector1
  3244. * @param normal direction of the normal
  3245. * @return the angle between vector0 and vector1
  3246. */
  3247. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3248. var v0 = vector0.clone().normalize();
  3249. var v1 = vector1.clone().normalize();
  3250. var dot = Vector3.Dot(v0, v1);
  3251. var n = Vector3.Cross(v0, v1);
  3252. if (Vector3.Dot(n, normal) > 0) {
  3253. return Math.acos(dot);
  3254. }
  3255. return -Math.acos(dot);
  3256. };
  3257. /**
  3258. * Returns a new Vector3 set from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @returns the new Vector3
  3262. */
  3263. Vector3.FromArray = function (array, offset) {
  3264. if (!offset) {
  3265. offset = 0;
  3266. }
  3267. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3268. };
  3269. /**
  3270. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3271. * This function is deprecated. Use FromArray instead
  3272. * @param array defines the source array
  3273. * @param offset defines the offset in the source array
  3274. * @returns the new Vector3
  3275. */
  3276. Vector3.FromFloatArray = function (array, offset) {
  3277. return Vector3.FromArray(array, offset);
  3278. };
  3279. /**
  3280. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3281. * @param array defines the source array
  3282. * @param offset defines the offset in the source array
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromArrayToRef = function (array, offset, result) {
  3286. result.x = array[offset];
  3287. result.y = array[offset + 1];
  3288. result.z = array[offset + 2];
  3289. };
  3290. /**
  3291. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3292. * This function is deprecated. Use FromArrayToRef instead.
  3293. * @param array defines the source array
  3294. * @param offset defines the offset in the source array
  3295. * @param result defines the Vector3 where to store the result
  3296. */
  3297. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3298. return Vector3.FromArrayToRef(array, offset, result);
  3299. };
  3300. /**
  3301. * Sets the given vector "result" with the given floats.
  3302. * @param x defines the x coordinate of the source
  3303. * @param y defines the y coordinate of the source
  3304. * @param z defines the z coordinate of the source
  3305. * @param result defines the Vector3 where to store the result
  3306. */
  3307. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3308. result.x = x;
  3309. result.y = y;
  3310. result.z = z;
  3311. };
  3312. /**
  3313. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3314. * @returns a new empty Vector3
  3315. */
  3316. Vector3.Zero = function () {
  3317. return new Vector3(0.0, 0.0, 0.0);
  3318. };
  3319. /**
  3320. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3321. * @returns a new unit Vector3
  3322. */
  3323. Vector3.One = function () {
  3324. return new Vector3(1.0, 1.0, 1.0);
  3325. };
  3326. /**
  3327. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3328. * @returns a new up Vector3
  3329. */
  3330. Vector3.Up = function () {
  3331. return new Vector3(0.0, 1.0, 0.0);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3335. * @returns a new down Vector3
  3336. */
  3337. Vector3.Down = function () {
  3338. return new Vector3(0.0, -1.0, 0.0);
  3339. };
  3340. /**
  3341. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3342. * @returns a new forward Vector3
  3343. */
  3344. Vector3.Forward = function () {
  3345. return new Vector3(0.0, 0.0, 1.0);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3349. * @returns a new right Vector3
  3350. */
  3351. Vector3.Right = function () {
  3352. return new Vector3(1.0, 0.0, 0.0);
  3353. };
  3354. /**
  3355. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3356. * @returns a new left Vector3
  3357. */
  3358. Vector3.Left = function () {
  3359. return new Vector3(-1.0, 0.0, 0.0);
  3360. };
  3361. /**
  3362. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3363. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3364. * @param vector defines the Vector3 to transform
  3365. * @param transformation defines the transformation matrix
  3366. * @returns the transformed Vector3
  3367. */
  3368. Vector3.TransformCoordinates = function (vector, transformation) {
  3369. var result = Vector3.Zero();
  3370. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3371. return result;
  3372. };
  3373. /**
  3374. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3375. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3376. * @param vector defines the Vector3 to transform
  3377. * @param transformation defines the transformation matrix
  3378. * @param result defines the Vector3 where to store the result
  3379. */
  3380. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3381. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3382. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3383. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3384. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3385. result.x = x / w;
  3386. result.y = y / w;
  3387. result.z = z / w;
  3388. };
  3389. /**
  3390. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3391. * This method computes tranformed coordinates only, not transformed direction vectors
  3392. * @param x define the x coordinate of the source vector
  3393. * @param y define the y coordinate of the source vector
  3394. * @param z define the z coordinate of the source vector
  3395. * @param transformation defines the transformation matrix
  3396. * @param result defines the Vector3 where to store the result
  3397. */
  3398. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3399. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3400. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3401. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3402. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3403. result.x = rx / rw;
  3404. result.y = ry / rw;
  3405. result.z = rz / rw;
  3406. };
  3407. /**
  3408. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3409. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3410. * @param vector defines the Vector3 to transform
  3411. * @param transformation defines the transformation matrix
  3412. * @returns the new Vector3
  3413. */
  3414. Vector3.TransformNormal = function (vector, transformation) {
  3415. var result = Vector3.Zero();
  3416. Vector3.TransformNormalToRef(vector, transformation, result);
  3417. return result;
  3418. };
  3419. /**
  3420. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3421. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3422. * @param vector defines the Vector3 to transform
  3423. * @param transformation defines the transformation matrix
  3424. * @param result defines the Vector3 where to store the result
  3425. */
  3426. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3427. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3428. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3429. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3430. result.x = x;
  3431. result.y = y;
  3432. result.z = z;
  3433. };
  3434. /**
  3435. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3436. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3437. * @param x define the x coordinate of the source vector
  3438. * @param y define the y coordinate of the source vector
  3439. * @param z define the z coordinate of the source vector
  3440. * @param transformation defines the transformation matrix
  3441. * @param result defines the Vector3 where to store the result
  3442. */
  3443. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3444. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3445. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3446. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3450. * @param value1 defines the first control point
  3451. * @param value2 defines the second control point
  3452. * @param value3 defines the third control point
  3453. * @param value4 defines the fourth control point
  3454. * @param amount defines the amount on the spline to use
  3455. * @returns the new Vector3
  3456. */
  3457. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3458. var squared = amount * amount;
  3459. var cubed = amount * squared;
  3460. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3461. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3462. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3463. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3464. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3465. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3466. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3467. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3468. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3469. return new Vector3(x, y, z);
  3470. };
  3471. /**
  3472. * 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"
  3473. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3474. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3475. * @param value defines the current value
  3476. * @param min defines the lower range value
  3477. * @param max defines the upper range value
  3478. * @returns the new Vector3
  3479. */
  3480. Vector3.Clamp = function (value, min, max) {
  3481. var x = value.x;
  3482. x = (x > max.x) ? max.x : x;
  3483. x = (x < min.x) ? min.x : x;
  3484. var y = value.y;
  3485. y = (y > max.y) ? max.y : y;
  3486. y = (y < min.y) ? min.y : y;
  3487. var z = value.z;
  3488. z = (z > max.z) ? max.z : z;
  3489. z = (z < min.z) ? min.z : z;
  3490. return new Vector3(x, y, z);
  3491. };
  3492. /**
  3493. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3494. * @param value1 defines the first control point
  3495. * @param tangent1 defines the first tangent vector
  3496. * @param value2 defines the second control point
  3497. * @param tangent2 defines the second tangent vector
  3498. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3499. * @returns the new Vector3
  3500. */
  3501. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3502. var squared = amount * amount;
  3503. var cubed = amount * squared;
  3504. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3505. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3506. var part3 = (cubed - (2.0 * squared)) + amount;
  3507. var part4 = cubed - squared;
  3508. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3509. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3510. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3511. return new Vector3(x, y, z);
  3512. };
  3513. /**
  3514. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3515. * @param start defines the start value
  3516. * @param end defines the end value
  3517. * @param amount max defines amount between both (between 0 and 1)
  3518. * @returns the new Vector3
  3519. */
  3520. Vector3.Lerp = function (start, end, amount) {
  3521. var result = new Vector3(0, 0, 0);
  3522. Vector3.LerpToRef(start, end, amount, result);
  3523. return result;
  3524. };
  3525. /**
  3526. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3527. * @param start defines the start value
  3528. * @param end defines the end value
  3529. * @param amount max defines amount between both (between 0 and 1)
  3530. * @param result defines the Vector3 where to store the result
  3531. */
  3532. Vector3.LerpToRef = function (start, end, amount, result) {
  3533. result.x = start.x + ((end.x - start.x) * amount);
  3534. result.y = start.y + ((end.y - start.y) * amount);
  3535. result.z = start.z + ((end.z - start.z) * amount);
  3536. };
  3537. /**
  3538. * Returns the dot product (float) between the vectors "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @returns the dot product
  3542. */
  3543. Vector3.Dot = function (left, right) {
  3544. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3545. };
  3546. /**
  3547. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3548. * The cross product is then orthogonal to both "left" and "right"
  3549. * @param left defines the left operand
  3550. * @param right defines the right operand
  3551. * @returns the cross product
  3552. */
  3553. Vector3.Cross = function (left, right) {
  3554. var result = Vector3.Zero();
  3555. Vector3.CrossToRef(left, right, result);
  3556. return result;
  3557. };
  3558. /**
  3559. * Sets the given vector "result" with the cross product of "left" and "right"
  3560. * The cross product is then orthogonal to both "left" and "right"
  3561. * @param left defines the left operand
  3562. * @param right defines the right operand
  3563. * @param result defines the Vector3 where to store the result
  3564. */
  3565. Vector3.CrossToRef = function (left, right, result) {
  3566. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3567. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3568. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3569. result.copyFrom(MathTmp.Vector3[0]);
  3570. };
  3571. /**
  3572. * Returns a new Vector3 as the normalization of the given vector
  3573. * @param vector defines the Vector3 to normalize
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Normalize = function (vector) {
  3577. var result = Vector3.Zero();
  3578. Vector3.NormalizeToRef(vector, result);
  3579. return result;
  3580. };
  3581. /**
  3582. * Sets the given vector "result" with the normalization of the given first vector
  3583. * @param vector defines the Vector3 to normalize
  3584. * @param result defines the Vector3 where to store the result
  3585. */
  3586. Vector3.NormalizeToRef = function (vector, result) {
  3587. result.copyFrom(vector);
  3588. result.normalize();
  3589. };
  3590. /**
  3591. * Project a Vector3 onto screen space
  3592. * @param vector defines the Vector3 to project
  3593. * @param world defines the world matrix to use
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @param viewport defines the screen viewport to use
  3596. * @returns the new Vector3
  3597. */
  3598. Vector3.Project = function (vector, world, transform, viewport) {
  3599. var cw = viewport.width;
  3600. var ch = viewport.height;
  3601. var cx = viewport.x;
  3602. var cy = viewport.y;
  3603. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3604. 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);
  3605. var matrix = MathTmp.Matrix[0];
  3606. world.multiplyToRef(transform, matrix);
  3607. matrix.multiplyToRef(viewportMatrix, matrix);
  3608. return Vector3.TransformCoordinates(vector, matrix);
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param transform defines the transform (view x projection) matrix to use
  3617. * @returns the new Vector3
  3618. */
  3619. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3620. var matrix = MathTmp.Matrix[0];
  3621. world.multiplyToRef(transform, matrix);
  3622. matrix.invert();
  3623. source.x = source.x / viewportWidth * 2 - 1;
  3624. source.y = -(source.y / viewportHeight * 2 - 1);
  3625. var vector = Vector3.TransformCoordinates(source, matrix);
  3626. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3627. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3628. vector = vector.scale(1.0 / num);
  3629. }
  3630. return vector;
  3631. };
  3632. /**
  3633. * Unproject from screen space to object space
  3634. * @param source defines the screen space Vector3 to use
  3635. * @param viewportWidth defines the current width of the viewport
  3636. * @param viewportHeight defines the current height of the viewport
  3637. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3638. * @param view defines the view matrix to use
  3639. * @param projection defines the projection matrix to use
  3640. * @returns the new Vector3
  3641. */
  3642. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3643. var result = Vector3.Zero();
  3644. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3645. return result;
  3646. };
  3647. /**
  3648. * Unproject from screen space to object space
  3649. * @param source defines the screen space Vector3 to use
  3650. * @param viewportWidth defines the current width of the viewport
  3651. * @param viewportHeight defines the current height of the viewport
  3652. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3653. * @param view defines the view matrix to use
  3654. * @param projection defines the projection matrix to use
  3655. * @param result defines the Vector3 where to store the result
  3656. */
  3657. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3658. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3659. };
  3660. /**
  3661. * Unproject from screen space to object space
  3662. * @param sourceX defines the screen space x coordinate to use
  3663. * @param sourceY defines the screen space y coordinate to use
  3664. * @param sourceZ defines the screen space z coordinate to use
  3665. * @param viewportWidth defines the current width of the viewport
  3666. * @param viewportHeight defines the current height of the viewport
  3667. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3668. * @param view defines the view matrix to use
  3669. * @param projection defines the projection matrix to use
  3670. * @param result defines the Vector3 where to store the result
  3671. */
  3672. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3673. var matrix = MathTmp.Matrix[0];
  3674. world.multiplyToRef(view, matrix);
  3675. matrix.multiplyToRef(projection, matrix);
  3676. matrix.invert();
  3677. var screenSource = MathTmp.Vector3[0];
  3678. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3679. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3680. screenSource.z = 2 * sourceZ - 1.0;
  3681. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3682. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3683. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3684. result.scaleInPlace(1.0 / num);
  3685. }
  3686. };
  3687. /**
  3688. * Gets the minimal coordinate values between two Vector3
  3689. * @param left defines the first operand
  3690. * @param right defines the second operand
  3691. * @returns the new Vector3
  3692. */
  3693. Vector3.Minimize = function (left, right) {
  3694. var min = left.clone();
  3695. min.minimizeInPlace(right);
  3696. return min;
  3697. };
  3698. /**
  3699. * Gets the maximal coordinate values between two Vector3
  3700. * @param left defines the first operand
  3701. * @param right defines the second operand
  3702. * @returns the new Vector3
  3703. */
  3704. Vector3.Maximize = function (left, right) {
  3705. var max = left.clone();
  3706. max.maximizeInPlace(right);
  3707. return max;
  3708. };
  3709. /**
  3710. * Returns the distance between the vectors "value1" and "value2"
  3711. * @param value1 defines the first operand
  3712. * @param value2 defines the second operand
  3713. * @returns the distance
  3714. */
  3715. Vector3.Distance = function (value1, value2) {
  3716. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3717. };
  3718. /**
  3719. * Returns the squared distance between the vectors "value1" and "value2"
  3720. * @param value1 defines the first operand
  3721. * @param value2 defines the second operand
  3722. * @returns the squared distance
  3723. */
  3724. Vector3.DistanceSquared = function (value1, value2) {
  3725. var x = value1.x - value2.x;
  3726. var y = value1.y - value2.y;
  3727. var z = value1.z - value2.z;
  3728. return (x * x) + (y * y) + (z * z);
  3729. };
  3730. /**
  3731. * Returns a new Vector3 located at the center between "value1" and "value2"
  3732. * @param value1 defines the first operand
  3733. * @param value2 defines the second operand
  3734. * @returns the new Vector3
  3735. */
  3736. Vector3.Center = function (value1, value2) {
  3737. var center = value1.add(value2);
  3738. center.scaleInPlace(0.5);
  3739. return center;
  3740. };
  3741. /**
  3742. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3743. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3744. * to something in order to rotate it from its local system to the given target system
  3745. * Note: axis1, axis2 and axis3 are normalized during this operation
  3746. * @param axis1 defines the first axis
  3747. * @param axis2 defines the second axis
  3748. * @param axis3 defines the third axis
  3749. * @returns a new Vector3
  3750. */
  3751. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3752. var rotation = Vector3.Zero();
  3753. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3754. return rotation;
  3755. };
  3756. /**
  3757. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3758. * @param axis1 defines the first axis
  3759. * @param axis2 defines the second axis
  3760. * @param axis3 defines the third axis
  3761. * @param ref defines the Vector3 where to store the result
  3762. */
  3763. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3764. var quat = MathTmp.Quaternion[0];
  3765. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3766. quat.toEulerAnglesToRef(ref);
  3767. };
  3768. return Vector3;
  3769. }());
  3770. BABYLON.Vector3 = Vector3;
  3771. //Vector4 class created for EulerAngle class conversion to Quaternion
  3772. var Vector4 = /** @class */ (function () {
  3773. /**
  3774. * Creates a Vector4 object from the given floats.
  3775. */
  3776. function Vector4(x, y, z, w) {
  3777. this.x = x;
  3778. this.y = y;
  3779. this.z = z;
  3780. this.w = w;
  3781. }
  3782. /**
  3783. * Returns the string with the Vector4 coordinates.
  3784. */
  3785. Vector4.prototype.toString = function () {
  3786. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3787. };
  3788. /**
  3789. * Returns the string "Vector4".
  3790. */
  3791. Vector4.prototype.getClassName = function () {
  3792. return "Vector4";
  3793. };
  3794. /**
  3795. * Returns the Vector4 hash code.
  3796. */
  3797. Vector4.prototype.getHashCode = function () {
  3798. var hash = this.x || 0;
  3799. hash = (hash * 397) ^ (this.y || 0);
  3800. hash = (hash * 397) ^ (this.z || 0);
  3801. hash = (hash * 397) ^ (this.w || 0);
  3802. return hash;
  3803. };
  3804. // Operators
  3805. /**
  3806. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3807. */
  3808. Vector4.prototype.asArray = function () {
  3809. var result = new Array();
  3810. this.toArray(result, 0);
  3811. return result;
  3812. };
  3813. /**
  3814. * Populates the given array from the given index with the Vector4 coordinates.
  3815. * Returns the Vector4.
  3816. */
  3817. Vector4.prototype.toArray = function (array, index) {
  3818. if (index === undefined) {
  3819. index = 0;
  3820. }
  3821. array[index] = this.x;
  3822. array[index + 1] = this.y;
  3823. array[index + 2] = this.z;
  3824. array[index + 3] = this.w;
  3825. return this;
  3826. };
  3827. /**
  3828. * Adds the given vector to the current Vector4.
  3829. * Returns the updated Vector4.
  3830. */
  3831. Vector4.prototype.addInPlace = function (otherVector) {
  3832. this.x += otherVector.x;
  3833. this.y += otherVector.y;
  3834. this.z += otherVector.z;
  3835. this.w += otherVector.w;
  3836. return this;
  3837. };
  3838. /**
  3839. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3840. */
  3841. Vector4.prototype.add = function (otherVector) {
  3842. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3843. };
  3844. /**
  3845. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3846. * Returns the current Vector4.
  3847. */
  3848. Vector4.prototype.addToRef = function (otherVector, result) {
  3849. result.x = this.x + otherVector.x;
  3850. result.y = this.y + otherVector.y;
  3851. result.z = this.z + otherVector.z;
  3852. result.w = this.w + otherVector.w;
  3853. return this;
  3854. };
  3855. /**
  3856. * Subtract in place the given vector from the current Vector4.
  3857. * Returns the updated Vector4.
  3858. */
  3859. Vector4.prototype.subtractInPlace = function (otherVector) {
  3860. this.x -= otherVector.x;
  3861. this.y -= otherVector.y;
  3862. this.z -= otherVector.z;
  3863. this.w -= otherVector.w;
  3864. return this;
  3865. };
  3866. /**
  3867. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3868. */
  3869. Vector4.prototype.subtract = function (otherVector) {
  3870. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3871. };
  3872. /**
  3873. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3874. * Returns the current Vector4.
  3875. */
  3876. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3877. result.x = this.x - otherVector.x;
  3878. result.y = this.y - otherVector.y;
  3879. result.z = this.z - otherVector.z;
  3880. result.w = this.w - otherVector.w;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3885. */
  3886. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3887. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3888. };
  3889. /**
  3890. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3891. * Returns the current Vector4.
  3892. */
  3893. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3894. result.x = this.x - x;
  3895. result.y = this.y - y;
  3896. result.z = this.z - z;
  3897. result.w = this.w - w;
  3898. return this;
  3899. };
  3900. /**
  3901. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3902. */
  3903. Vector4.prototype.negate = function () {
  3904. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3905. };
  3906. /**
  3907. * Multiplies the current Vector4 coordinates by scale (float).
  3908. * Returns the updated Vector4.
  3909. */
  3910. Vector4.prototype.scaleInPlace = function (scale) {
  3911. this.x *= scale;
  3912. this.y *= scale;
  3913. this.z *= scale;
  3914. this.w *= scale;
  3915. return this;
  3916. };
  3917. /**
  3918. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3919. */
  3920. Vector4.prototype.scale = function (scale) {
  3921. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3922. };
  3923. /**
  3924. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3925. * Returns the current Vector4.
  3926. */
  3927. Vector4.prototype.scaleToRef = function (scale, result) {
  3928. result.x = this.x * scale;
  3929. result.y = this.y * scale;
  3930. result.z = this.z * scale;
  3931. result.w = this.w * scale;
  3932. return this;
  3933. };
  3934. /**
  3935. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3936. * @param scale defines the scale factor
  3937. * @param result defines the Vector4 object where to store the result
  3938. * @returns the unmodified current Vector4
  3939. */
  3940. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3941. result.x += this.x * scale;
  3942. result.y += this.y * scale;
  3943. result.z += this.z * scale;
  3944. result.w += this.w * scale;
  3945. return this;
  3946. };
  3947. /**
  3948. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3949. */
  3950. Vector4.prototype.equals = function (otherVector) {
  3951. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3952. };
  3953. /**
  3954. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3955. */
  3956. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3957. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3958. return otherVector
  3959. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3960. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3961. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3962. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3963. };
  3964. /**
  3965. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3966. */
  3967. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3968. return this.x === x && this.y === y && this.z === z && this.w === w;
  3969. };
  3970. /**
  3971. * Multiplies in place the current Vector4 by the given one.
  3972. * Returns the updated Vector4.
  3973. */
  3974. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3975. this.x *= otherVector.x;
  3976. this.y *= otherVector.y;
  3977. this.z *= otherVector.z;
  3978. this.w *= otherVector.w;
  3979. return this;
  3980. };
  3981. /**
  3982. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3983. */
  3984. Vector4.prototype.multiply = function (otherVector) {
  3985. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3986. };
  3987. /**
  3988. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3989. * Returns the current Vector4.
  3990. */
  3991. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3992. result.x = this.x * otherVector.x;
  3993. result.y = this.y * otherVector.y;
  3994. result.z = this.z * otherVector.z;
  3995. result.w = this.w * otherVector.w;
  3996. return this;
  3997. };
  3998. /**
  3999. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4000. */
  4001. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4002. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4003. };
  4004. /**
  4005. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4006. */
  4007. Vector4.prototype.divide = function (otherVector) {
  4008. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4009. };
  4010. /**
  4011. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4012. * Returns the current Vector4.
  4013. */
  4014. Vector4.prototype.divideToRef = function (otherVector, result) {
  4015. result.x = this.x / otherVector.x;
  4016. result.y = this.y / otherVector.y;
  4017. result.z = this.z / otherVector.z;
  4018. result.w = this.w / otherVector.w;
  4019. return this;
  4020. };
  4021. /**
  4022. * Divides the current Vector3 coordinates by the given ones.
  4023. * @returns the updated Vector3.
  4024. */
  4025. Vector4.prototype.divideInPlace = function (otherVector) {
  4026. return this.divideToRef(otherVector, this);
  4027. };
  4028. /**
  4029. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4030. * @param other defines the second operand
  4031. * @returns the current updated Vector4
  4032. */
  4033. Vector4.prototype.minimizeInPlace = function (other) {
  4034. if (other.x < this.x)
  4035. this.x = other.x;
  4036. if (other.y < this.y)
  4037. this.y = other.y;
  4038. if (other.z < this.z)
  4039. this.z = other.z;
  4040. if (other.w < this.w)
  4041. this.w = other.w;
  4042. return this;
  4043. };
  4044. /**
  4045. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4046. * @param other defines the second operand
  4047. * @returns the current updated Vector4
  4048. */
  4049. Vector4.prototype.maximizeInPlace = function (other) {
  4050. if (other.x > this.x)
  4051. this.x = other.x;
  4052. if (other.y > this.y)
  4053. this.y = other.y;
  4054. if (other.z > this.z)
  4055. this.z = other.z;
  4056. if (other.w > this.w)
  4057. this.w = other.w;
  4058. return this;
  4059. };
  4060. // Properties
  4061. /**
  4062. * Returns the Vector4 length (float).
  4063. */
  4064. Vector4.prototype.length = function () {
  4065. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4066. };
  4067. /**
  4068. * Returns the Vector4 squared length (float).
  4069. */
  4070. Vector4.prototype.lengthSquared = function () {
  4071. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4072. };
  4073. // Methods
  4074. /**
  4075. * Normalizes in place the Vector4.
  4076. * Returns the updated Vector4.
  4077. */
  4078. Vector4.prototype.normalize = function () {
  4079. var len = this.length();
  4080. if (len === 0)
  4081. return this;
  4082. var num = 1.0 / len;
  4083. this.x *= num;
  4084. this.y *= num;
  4085. this.z *= num;
  4086. this.w *= num;
  4087. return this;
  4088. };
  4089. /**
  4090. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4091. */
  4092. Vector4.prototype.toVector3 = function () {
  4093. return new Vector3(this.x, this.y, this.z);
  4094. };
  4095. /**
  4096. * Returns a new Vector4 copied from the current one.
  4097. */
  4098. Vector4.prototype.clone = function () {
  4099. return new Vector4(this.x, this.y, this.z, this.w);
  4100. };
  4101. /**
  4102. * Updates the current Vector4 with the given one coordinates.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.copyFrom = function (source) {
  4106. this.x = source.x;
  4107. this.y = source.y;
  4108. this.z = source.z;
  4109. this.w = source.w;
  4110. return this;
  4111. };
  4112. /**
  4113. * Updates the current Vector4 coordinates with the given floats.
  4114. * Returns the updated Vector4.
  4115. */
  4116. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4117. this.x = x;
  4118. this.y = y;
  4119. this.z = z;
  4120. this.w = w;
  4121. return this;
  4122. };
  4123. /**
  4124. * Updates the current Vector4 coordinates with the given floats.
  4125. * Returns the updated Vector4.
  4126. */
  4127. Vector4.prototype.set = function (x, y, z, w) {
  4128. return this.copyFromFloats(x, y, z, w);
  4129. };
  4130. // Statics
  4131. /**
  4132. * Returns a new Vector4 set from the starting index of the given array.
  4133. */
  4134. Vector4.FromArray = function (array, offset) {
  4135. if (!offset) {
  4136. offset = 0;
  4137. }
  4138. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4139. };
  4140. /**
  4141. * Updates the given vector "result" from the starting index of the given array.
  4142. */
  4143. Vector4.FromArrayToRef = function (array, offset, result) {
  4144. result.x = array[offset];
  4145. result.y = array[offset + 1];
  4146. result.z = array[offset + 2];
  4147. result.w = array[offset + 3];
  4148. };
  4149. /**
  4150. * Updates the given vector "result" from the starting index of the given Float32Array.
  4151. */
  4152. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4153. Vector4.FromArrayToRef(array, offset, result);
  4154. };
  4155. /**
  4156. * Updates the given vector "result" coordinates from the given floats.
  4157. */
  4158. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4159. result.x = x;
  4160. result.y = y;
  4161. result.z = z;
  4162. result.w = w;
  4163. };
  4164. /**
  4165. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4166. */
  4167. Vector4.Zero = function () {
  4168. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4169. };
  4170. /**
  4171. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4172. */
  4173. Vector4.One = function () {
  4174. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4175. };
  4176. /**
  4177. * Returns a new normalized Vector4 from the given one.
  4178. */
  4179. Vector4.Normalize = function (vector) {
  4180. var result = Vector4.Zero();
  4181. Vector4.NormalizeToRef(vector, result);
  4182. return result;
  4183. };
  4184. /**
  4185. * Updates the given vector "result" from the normalization of the given one.
  4186. */
  4187. Vector4.NormalizeToRef = function (vector, result) {
  4188. result.copyFrom(vector);
  4189. result.normalize();
  4190. };
  4191. Vector4.Minimize = function (left, right) {
  4192. var min = left.clone();
  4193. min.minimizeInPlace(right);
  4194. return min;
  4195. };
  4196. Vector4.Maximize = function (left, right) {
  4197. var max = left.clone();
  4198. max.maximizeInPlace(right);
  4199. return max;
  4200. };
  4201. /**
  4202. * Returns the distance (float) between the vectors "value1" and "value2".
  4203. */
  4204. Vector4.Distance = function (value1, value2) {
  4205. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4206. };
  4207. /**
  4208. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4209. */
  4210. Vector4.DistanceSquared = function (value1, value2) {
  4211. var x = value1.x - value2.x;
  4212. var y = value1.y - value2.y;
  4213. var z = value1.z - value2.z;
  4214. var w = value1.w - value2.w;
  4215. return (x * x) + (y * y) + (z * z) + (w * w);
  4216. };
  4217. /**
  4218. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4219. */
  4220. Vector4.Center = function (value1, value2) {
  4221. var center = value1.add(value2);
  4222. center.scaleInPlace(0.5);
  4223. return center;
  4224. };
  4225. /**
  4226. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormal = function (vector, transformation) {
  4230. var result = Vector4.Zero();
  4231. Vector4.TransformNormalToRef(vector, transformation, result);
  4232. return result;
  4233. };
  4234. /**
  4235. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4236. * This methods computes transformed normalized direction vectors only.
  4237. */
  4238. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4239. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4240. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4241. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4242. result.x = x;
  4243. result.y = y;
  4244. result.z = z;
  4245. result.w = vector.w;
  4246. };
  4247. /**
  4248. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4249. * This methods computes transformed normalized direction vectors only.
  4250. */
  4251. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4252. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4253. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4254. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4255. result.w = w;
  4256. };
  4257. return Vector4;
  4258. }());
  4259. BABYLON.Vector4 = Vector4;
  4260. var Size = /** @class */ (function () {
  4261. /**
  4262. * Creates a Size object from the given width and height (floats).
  4263. */
  4264. function Size(width, height) {
  4265. this.width = width;
  4266. this.height = height;
  4267. }
  4268. // Returns a string with the Size width and height.
  4269. Size.prototype.toString = function () {
  4270. return "{W: " + this.width + ", H: " + this.height + "}";
  4271. };
  4272. /**
  4273. * Returns the string "Size"
  4274. */
  4275. Size.prototype.getClassName = function () {
  4276. return "Size";
  4277. };
  4278. /**
  4279. * Returns the Size hash code.
  4280. */
  4281. Size.prototype.getHashCode = function () {
  4282. var hash = this.width || 0;
  4283. hash = (hash * 397) ^ (this.height || 0);
  4284. return hash;
  4285. };
  4286. /**
  4287. * Updates the current size from the given one.
  4288. * Returns the updated Size.
  4289. */
  4290. Size.prototype.copyFrom = function (src) {
  4291. this.width = src.width;
  4292. this.height = src.height;
  4293. };
  4294. /**
  4295. * Updates in place the current Size from the given floats.
  4296. * Returns the updated Size.
  4297. */
  4298. Size.prototype.copyFromFloats = function (width, height) {
  4299. this.width = width;
  4300. this.height = height;
  4301. return this;
  4302. };
  4303. /**
  4304. * Updates in place the current Size from the given floats.
  4305. * Returns the updated Size.
  4306. */
  4307. Size.prototype.set = function (width, height) {
  4308. return this.copyFromFloats(width, height);
  4309. };
  4310. /**
  4311. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4312. */
  4313. Size.prototype.multiplyByFloats = function (w, h) {
  4314. return new Size(this.width * w, this.height * h);
  4315. };
  4316. /**
  4317. * Returns a new Size copied from the given one.
  4318. */
  4319. Size.prototype.clone = function () {
  4320. return new Size(this.width, this.height);
  4321. };
  4322. /**
  4323. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4324. */
  4325. Size.prototype.equals = function (other) {
  4326. if (!other) {
  4327. return false;
  4328. }
  4329. return (this.width === other.width) && (this.height === other.height);
  4330. };
  4331. Object.defineProperty(Size.prototype, "surface", {
  4332. /**
  4333. * Returns the surface of the Size : width * height (float).
  4334. */
  4335. get: function () {
  4336. return this.width * this.height;
  4337. },
  4338. enumerable: true,
  4339. configurable: true
  4340. });
  4341. /**
  4342. * Returns a new Size set to (0.0, 0.0)
  4343. */
  4344. Size.Zero = function () {
  4345. return new Size(0.0, 0.0);
  4346. };
  4347. /**
  4348. * Returns a new Size set as the addition result of the current Size and the given one.
  4349. */
  4350. Size.prototype.add = function (otherSize) {
  4351. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4352. return r;
  4353. };
  4354. /**
  4355. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4356. */
  4357. Size.prototype.subtract = function (otherSize) {
  4358. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4359. return r;
  4360. };
  4361. /**
  4362. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4363. */
  4364. Size.Lerp = function (start, end, amount) {
  4365. var w = start.width + ((end.width - start.width) * amount);
  4366. var h = start.height + ((end.height - start.height) * amount);
  4367. return new Size(w, h);
  4368. };
  4369. return Size;
  4370. }());
  4371. BABYLON.Size = Size;
  4372. /**
  4373. * Class used to store quaternion data
  4374. * @see https://en.wikipedia.org/wiki/Quaternion
  4375. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4376. */
  4377. var Quaternion = /** @class */ (function () {
  4378. /**
  4379. * Creates a new Quaternion from the given floats
  4380. * @param x defines the first component (0 by default)
  4381. * @param y defines the second component (0 by default)
  4382. * @param z defines the third component (0 by default)
  4383. * @param w defines the fourth component (1.0 by default)
  4384. */
  4385. function Quaternion(
  4386. /** defines the first component (0 by default) */
  4387. x,
  4388. /** defines the second component (0 by default) */
  4389. y,
  4390. /** defines the third component (0 by default) */
  4391. z,
  4392. /** defines the fourth component (1.0 by default) */
  4393. w) {
  4394. if (x === void 0) { x = 0.0; }
  4395. if (y === void 0) { y = 0.0; }
  4396. if (z === void 0) { z = 0.0; }
  4397. if (w === void 0) { w = 1.0; }
  4398. this.x = x;
  4399. this.y = y;
  4400. this.z = z;
  4401. this.w = w;
  4402. }
  4403. /**
  4404. * Gets a string representation for the current quaternion
  4405. * @returns a string with the Quaternion coordinates
  4406. */
  4407. Quaternion.prototype.toString = function () {
  4408. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4409. };
  4410. /**
  4411. * Gets the class name of the quaternion
  4412. * @returns the string "Quaternion"
  4413. */
  4414. Quaternion.prototype.getClassName = function () {
  4415. return "Quaternion";
  4416. };
  4417. /**
  4418. * Gets a hash code for this quaternion
  4419. * @returns the quaternion hash code
  4420. */
  4421. Quaternion.prototype.getHashCode = function () {
  4422. var hash = this.x || 0;
  4423. hash = (hash * 397) ^ (this.y || 0);
  4424. hash = (hash * 397) ^ (this.z || 0);
  4425. hash = (hash * 397) ^ (this.w || 0);
  4426. return hash;
  4427. };
  4428. /**
  4429. * Copy the quaternion to an array
  4430. * @returns a new array populated with 4 elements from the quaternion coordinates
  4431. */
  4432. Quaternion.prototype.asArray = function () {
  4433. return [this.x, this.y, this.z, this.w];
  4434. };
  4435. /**
  4436. * Check if two quaternions are equals
  4437. * @param otherQuaternion defines the second operand
  4438. * @return true if the current quaternion and the given one coordinates are strictly equals
  4439. */
  4440. Quaternion.prototype.equals = function (otherQuaternion) {
  4441. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4442. };
  4443. /**
  4444. * Clone the current quaternion
  4445. * @returns a new quaternion copied from the current one
  4446. */
  4447. Quaternion.prototype.clone = function () {
  4448. return new Quaternion(this.x, this.y, this.z, this.w);
  4449. };
  4450. /**
  4451. * Copy a quaternion to the current one
  4452. * @param other defines the other quaternion
  4453. * @returns the updated current quaternion
  4454. */
  4455. Quaternion.prototype.copyFrom = function (other) {
  4456. this.x = other.x;
  4457. this.y = other.y;
  4458. this.z = other.z;
  4459. this.w = other.w;
  4460. return this;
  4461. };
  4462. /**
  4463. * Updates the current quaternion with the given float coordinates
  4464. * @param x defines the x coordinate
  4465. * @param y defines the y coordinate
  4466. * @param z defines the z coordinate
  4467. * @param w defines the w coordinate
  4468. * @returns the updated current quaternion
  4469. */
  4470. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4471. this.x = x;
  4472. this.y = y;
  4473. this.z = z;
  4474. this.w = w;
  4475. return this;
  4476. };
  4477. /**
  4478. * Updates the current quaternion from the given float coordinates
  4479. * @param x defines the x coordinate
  4480. * @param y defines the y coordinate
  4481. * @param z defines the z coordinate
  4482. * @param w defines the w coordinate
  4483. * @returns the updated current quaternion
  4484. */
  4485. Quaternion.prototype.set = function (x, y, z, w) {
  4486. return this.copyFromFloats(x, y, z, w);
  4487. };
  4488. /**
  4489. * Adds two quaternions
  4490. * @param other defines the second operand
  4491. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4492. */
  4493. Quaternion.prototype.add = function (other) {
  4494. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4495. };
  4496. /**
  4497. * Add a quaternion to the current one
  4498. * @param other defines the quaternion to add
  4499. * @returns the current quaternion
  4500. */
  4501. Quaternion.prototype.addInPlace = function (other) {
  4502. this.x += other.x;
  4503. this.y += other.y;
  4504. this.z += other.z;
  4505. this.w += other.w;
  4506. return this;
  4507. };
  4508. /**
  4509. * Subtract two quaternions
  4510. * @param other defines the second operand
  4511. * @returns a new quaternion as the subtraction result of the given one from the current one
  4512. */
  4513. Quaternion.prototype.subtract = function (other) {
  4514. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4515. };
  4516. /**
  4517. * Multiplies the current quaternion by a scale factor
  4518. * @param value defines the scale factor
  4519. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4520. */
  4521. Quaternion.prototype.scale = function (value) {
  4522. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4523. };
  4524. /**
  4525. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4526. * @param scale defines the scale factor
  4527. * @param result defines the Quaternion object where to store the result
  4528. * @returns the unmodified current quaternion
  4529. */
  4530. Quaternion.prototype.scaleToRef = function (scale, result) {
  4531. result.x = this.x * scale;
  4532. result.y = this.y * scale;
  4533. result.z = this.z * scale;
  4534. result.w = this.w * scale;
  4535. return this;
  4536. };
  4537. /**
  4538. * Multiplies in place the current quaternion by a scale factor
  4539. * @param value defines the scale factor
  4540. * @returns the current modified quaternion
  4541. */
  4542. Quaternion.prototype.scaleInPlace = function (value) {
  4543. this.x *= value;
  4544. this.y *= value;
  4545. this.z *= value;
  4546. this.w *= value;
  4547. return this;
  4548. };
  4549. /**
  4550. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4551. * @param scale defines the scale factor
  4552. * @param result defines the Quaternion object where to store the result
  4553. * @returns the unmodified current quaternion
  4554. */
  4555. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4556. result.x += this.x * scale;
  4557. result.y += this.y * scale;
  4558. result.z += this.z * scale;
  4559. result.w += this.w * scale;
  4560. return this;
  4561. };
  4562. /**
  4563. * Multiplies two quaternions
  4564. * @param q1 defines the second operand
  4565. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4566. */
  4567. Quaternion.prototype.multiply = function (q1) {
  4568. var result = new Quaternion(0, 0, 0, 1.0);
  4569. this.multiplyToRef(q1, result);
  4570. return result;
  4571. };
  4572. /**
  4573. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4574. * @param q1 defines the second operand
  4575. * @param result defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4579. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4580. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4581. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4582. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4583. result.copyFromFloats(x, y, z, w);
  4584. return this;
  4585. };
  4586. /**
  4587. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4588. * @param q1 defines the second operand
  4589. * @returns the currentupdated quaternion
  4590. */
  4591. Quaternion.prototype.multiplyInPlace = function (q1) {
  4592. this.multiplyToRef(q1, this);
  4593. return this;
  4594. };
  4595. /**
  4596. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4597. * @param ref defines the target quaternion
  4598. * @returns the current quaternion
  4599. */
  4600. Quaternion.prototype.conjugateToRef = function (ref) {
  4601. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4602. return this;
  4603. };
  4604. /**
  4605. * Conjugates in place (1-q) the current quaternion
  4606. * @returns the current updated quaternion
  4607. */
  4608. Quaternion.prototype.conjugateInPlace = function () {
  4609. this.x *= -1;
  4610. this.y *= -1;
  4611. this.z *= -1;
  4612. return this;
  4613. };
  4614. /**
  4615. * Conjugates in place (1-q) the current quaternion
  4616. * @returns a new quaternion
  4617. */
  4618. Quaternion.prototype.conjugate = function () {
  4619. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4620. return result;
  4621. };
  4622. /**
  4623. * Gets length of current quaternion
  4624. * @returns the quaternion length (float)
  4625. */
  4626. Quaternion.prototype.length = function () {
  4627. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4628. };
  4629. /**
  4630. * Normalize in place the current quaternion
  4631. * @returns the current updated quaternion
  4632. */
  4633. Quaternion.prototype.normalize = function () {
  4634. var length = 1.0 / this.length();
  4635. this.x *= length;
  4636. this.y *= length;
  4637. this.z *= length;
  4638. this.w *= length;
  4639. return this;
  4640. };
  4641. /**
  4642. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4643. * @param order is a reserved parameter and is ignore for now
  4644. * @returns a new Vector3 containing the Euler angles
  4645. */
  4646. Quaternion.prototype.toEulerAngles = function (order) {
  4647. if (order === void 0) { order = "YZX"; }
  4648. var result = Vector3.Zero();
  4649. this.toEulerAnglesToRef(result, order);
  4650. return result;
  4651. };
  4652. /**
  4653. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4654. * @param result defines the vector which will be filled with the Euler angles
  4655. * @param order is a reserved parameter and is ignore for now
  4656. * @returns the current unchanged quaternion
  4657. */
  4658. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4659. if (order === void 0) { order = "YZX"; }
  4660. var qz = this.z;
  4661. var qx = this.x;
  4662. var qy = this.y;
  4663. var qw = this.w;
  4664. var sqw = qw * qw;
  4665. var sqz = qz * qz;
  4666. var sqx = qx * qx;
  4667. var sqy = qy * qy;
  4668. var zAxisY = qy * qz - qx * qw;
  4669. var limit = .4999999;
  4670. if (zAxisY < -limit) {
  4671. result.y = 2 * Math.atan2(qy, qw);
  4672. result.x = Math.PI / 2;
  4673. result.z = 0;
  4674. }
  4675. else if (zAxisY > limit) {
  4676. result.y = 2 * Math.atan2(qy, qw);
  4677. result.x = -Math.PI / 2;
  4678. result.z = 0;
  4679. }
  4680. else {
  4681. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4682. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4683. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4684. }
  4685. return this;
  4686. };
  4687. /**
  4688. * Updates the given rotation matrix with the current quaternion values
  4689. * @param result defines the target matrix
  4690. * @returns the current unchanged quaternion
  4691. */
  4692. Quaternion.prototype.toRotationMatrix = function (result) {
  4693. var xx = this.x * this.x;
  4694. var yy = this.y * this.y;
  4695. var zz = this.z * this.z;
  4696. var xy = this.x * this.y;
  4697. var zw = this.z * this.w;
  4698. var zx = this.z * this.x;
  4699. var yw = this.y * this.w;
  4700. var yz = this.y * this.z;
  4701. var xw = this.x * this.w;
  4702. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4703. result.m[1] = 2.0 * (xy + zw);
  4704. result.m[2] = 2.0 * (zx - yw);
  4705. result.m[3] = 0;
  4706. result.m[4] = 2.0 * (xy - zw);
  4707. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4708. result.m[6] = 2.0 * (yz + xw);
  4709. result.m[7] = 0;
  4710. result.m[8] = 2.0 * (zx + yw);
  4711. result.m[9] = 2.0 * (yz - xw);
  4712. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4713. result.m[11] = 0;
  4714. result.m[12] = 0;
  4715. result.m[13] = 0;
  4716. result.m[14] = 0;
  4717. result.m[15] = 1.0;
  4718. result._markAsUpdated();
  4719. return this;
  4720. };
  4721. /**
  4722. * Updates the current quaternion from the given rotation matrix values
  4723. * @param matrix defines the source matrix
  4724. * @returns the current updated quaternion
  4725. */
  4726. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4727. Quaternion.FromRotationMatrixToRef(matrix, this);
  4728. return this;
  4729. };
  4730. // Statics
  4731. /**
  4732. * Creates a new quaternion from a rotation matrix
  4733. * @param matrix defines the source matrix
  4734. * @returns a new quaternion created from the given rotation matrix values
  4735. */
  4736. Quaternion.FromRotationMatrix = function (matrix) {
  4737. var result = new Quaternion();
  4738. Quaternion.FromRotationMatrixToRef(matrix, result);
  4739. return result;
  4740. };
  4741. /**
  4742. * Updates the given quaternion with the given rotation matrix values
  4743. * @param matrix defines the source matrix
  4744. * @param result defines the target quaternion
  4745. */
  4746. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4747. var data = matrix.m;
  4748. var m11 = data[0], m12 = data[4], m13 = data[8];
  4749. var m21 = data[1], m22 = data[5], m23 = data[9];
  4750. var m31 = data[2], m32 = data[6], m33 = data[10];
  4751. var trace = m11 + m22 + m33;
  4752. var s;
  4753. if (trace > 0) {
  4754. s = 0.5 / Math.sqrt(trace + 1.0);
  4755. result.w = 0.25 / s;
  4756. result.x = (m32 - m23) * s;
  4757. result.y = (m13 - m31) * s;
  4758. result.z = (m21 - m12) * s;
  4759. }
  4760. else if (m11 > m22 && m11 > m33) {
  4761. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4762. result.w = (m32 - m23) / s;
  4763. result.x = 0.25 * s;
  4764. result.y = (m12 + m21) / s;
  4765. result.z = (m13 + m31) / s;
  4766. }
  4767. else if (m22 > m33) {
  4768. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4769. result.w = (m13 - m31) / s;
  4770. result.x = (m12 + m21) / s;
  4771. result.y = 0.25 * s;
  4772. result.z = (m23 + m32) / s;
  4773. }
  4774. else {
  4775. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4776. result.w = (m21 - m12) / s;
  4777. result.x = (m13 + m31) / s;
  4778. result.y = (m23 + m32) / s;
  4779. result.z = 0.25 * s;
  4780. }
  4781. };
  4782. /**
  4783. * Returns the dot product (float) between the quaternions "left" and "right"
  4784. * @param left defines the left operand
  4785. * @param right defines the right operand
  4786. * @returns the dot product
  4787. */
  4788. Quaternion.Dot = function (left, right) {
  4789. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4790. };
  4791. /**
  4792. * Checks if the two quaternions are close to each other
  4793. * @param quat0 defines the first quaternion to check
  4794. * @param quat1 defines the second quaternion to check
  4795. * @returns true if the two quaternions are close to each other
  4796. */
  4797. Quaternion.AreClose = function (quat0, quat1) {
  4798. var dot = Quaternion.Dot(quat0, quat1);
  4799. return dot >= 0;
  4800. };
  4801. /**
  4802. * Creates an empty quaternion
  4803. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4804. */
  4805. Quaternion.Zero = function () {
  4806. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4807. };
  4808. /**
  4809. * Inverse a given quaternion
  4810. * @param q defines the source quaternion
  4811. * @returns a new quaternion as the inverted current quaternion
  4812. */
  4813. Quaternion.Inverse = function (q) {
  4814. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4815. };
  4816. /**
  4817. * Creates an identity quaternion
  4818. * @returns the identity quaternion
  4819. */
  4820. Quaternion.Identity = function () {
  4821. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4822. };
  4823. /**
  4824. * Gets a boolean indicating if the given quaternion is identity
  4825. * @param quaternion defines the quaternion to check
  4826. * @returns true if the quaternion is identity
  4827. */
  4828. Quaternion.IsIdentity = function (quaternion) {
  4829. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4830. };
  4831. /**
  4832. * Creates a quaternion from a rotation around an axis
  4833. * @param axis defines the axis to use
  4834. * @param angle defines the angle to use
  4835. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4836. */
  4837. Quaternion.RotationAxis = function (axis, angle) {
  4838. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4839. };
  4840. /**
  4841. * Creates a rotation around an axis and stores it into the given quaternion
  4842. * @param axis defines the axis to use
  4843. * @param angle defines the angle to use
  4844. * @param result defines the target quaternion
  4845. * @returns the target quaternion
  4846. */
  4847. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4848. var sin = Math.sin(angle / 2);
  4849. axis.normalize();
  4850. result.w = Math.cos(angle / 2);
  4851. result.x = axis.x * sin;
  4852. result.y = axis.y * sin;
  4853. result.z = axis.z * sin;
  4854. return result;
  4855. };
  4856. /**
  4857. * Creates a new quaternion from data stored into an array
  4858. * @param array defines the data source
  4859. * @param offset defines the offset in the source array where the data starts
  4860. * @returns a new quaternion
  4861. */
  4862. Quaternion.FromArray = function (array, offset) {
  4863. if (!offset) {
  4864. offset = 0;
  4865. }
  4866. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4867. };
  4868. /**
  4869. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4870. * @param yaw defines the rotation around Y axis
  4871. * @param pitch defines the rotation around X axis
  4872. * @param roll defines the rotation around Z axis
  4873. * @returns the new quaternion
  4874. */
  4875. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4876. var q = new Quaternion();
  4877. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4878. return q;
  4879. };
  4880. /**
  4881. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4882. * @param yaw defines the rotation around Y axis
  4883. * @param pitch defines the rotation around X axis
  4884. * @param roll defines the rotation around Z axis
  4885. * @param result defines the target quaternion
  4886. */
  4887. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4888. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4889. var halfRoll = roll * 0.5;
  4890. var halfPitch = pitch * 0.5;
  4891. var halfYaw = yaw * 0.5;
  4892. var sinRoll = Math.sin(halfRoll);
  4893. var cosRoll = Math.cos(halfRoll);
  4894. var sinPitch = Math.sin(halfPitch);
  4895. var cosPitch = Math.cos(halfPitch);
  4896. var sinYaw = Math.sin(halfYaw);
  4897. var cosYaw = Math.cos(halfYaw);
  4898. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4899. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4900. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4901. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4902. };
  4903. /**
  4904. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4905. * @param alpha defines the rotation around first axis
  4906. * @param beta defines the rotation around second axis
  4907. * @param gamma defines the rotation around third axis
  4908. * @returns the new quaternion
  4909. */
  4910. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4911. var result = new Quaternion();
  4912. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4913. return result;
  4914. };
  4915. /**
  4916. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4917. * @param alpha defines the rotation around first axis
  4918. * @param beta defines the rotation around second axis
  4919. * @param gamma defines the rotation around third axis
  4920. * @param result defines the target quaternion
  4921. */
  4922. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4923. // Produces a quaternion from Euler angles in the z-x-z orientation
  4924. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4925. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4926. var halfBeta = beta * 0.5;
  4927. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4928. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4929. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4930. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4931. };
  4932. /**
  4933. * 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)
  4934. * @param axis1 defines the first axis
  4935. * @param axis2 defines the second axis
  4936. * @param axis3 defines the third axis
  4937. * @returns the new quaternion
  4938. */
  4939. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4940. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4941. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4942. return quat;
  4943. };
  4944. /**
  4945. * 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
  4946. * @param axis1 defines the first axis
  4947. * @param axis2 defines the second axis
  4948. * @param axis3 defines the third axis
  4949. * @param ref defines the target quaternion
  4950. */
  4951. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4952. var rotMat = MathTmp.Matrix[0];
  4953. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4954. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4955. };
  4956. /**
  4957. * Interpolates between two quaternions
  4958. * @param left defines first quaternion
  4959. * @param right defines second quaternion
  4960. * @param amount defines the gradient to use
  4961. * @returns the new interpolated quaternion
  4962. */
  4963. Quaternion.Slerp = function (left, right, amount) {
  4964. var result = Quaternion.Identity();
  4965. Quaternion.SlerpToRef(left, right, amount, result);
  4966. return result;
  4967. };
  4968. /**
  4969. * Interpolates between two quaternions and stores it into a target quaternion
  4970. * @param left defines first quaternion
  4971. * @param right defines second quaternion
  4972. * @param amount defines the gradient to use
  4973. * @param result defines the target quaternion
  4974. */
  4975. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4976. var num2;
  4977. var num3;
  4978. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4979. var flag = false;
  4980. if (num4 < 0) {
  4981. flag = true;
  4982. num4 = -num4;
  4983. }
  4984. if (num4 > 0.999999) {
  4985. num3 = 1 - amount;
  4986. num2 = flag ? -amount : amount;
  4987. }
  4988. else {
  4989. var num5 = Math.acos(num4);
  4990. var num6 = (1.0 / Math.sin(num5));
  4991. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4992. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4993. }
  4994. result.x = (num3 * left.x) + (num2 * right.x);
  4995. result.y = (num3 * left.y) + (num2 * right.y);
  4996. result.z = (num3 * left.z) + (num2 * right.z);
  4997. result.w = (num3 * left.w) + (num2 * right.w);
  4998. };
  4999. /**
  5000. * Interpolate between two quaternions using Hermite interpolation
  5001. * @param value1 defines first quaternion
  5002. * @param tangent1 defines the incoming tangent
  5003. * @param value2 defines second quaternion
  5004. * @param tangent2 defines the outgoing tangent
  5005. * @param amount defines the target quaternion
  5006. * @returns the new interpolated quaternion
  5007. */
  5008. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5009. var squared = amount * amount;
  5010. var cubed = amount * squared;
  5011. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5012. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5013. var part3 = (cubed - (2.0 * squared)) + amount;
  5014. var part4 = cubed - squared;
  5015. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5016. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5017. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5018. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5019. return new Quaternion(x, y, z, w);
  5020. };
  5021. return Quaternion;
  5022. }());
  5023. BABYLON.Quaternion = Quaternion;
  5024. /**
  5025. * Class used to store matrix data (4x4)
  5026. */
  5027. var Matrix = /** @class */ (function () {
  5028. /**
  5029. * Creates an empty matrix (filled with zeros)
  5030. */
  5031. function Matrix() {
  5032. this._isIdentity = false;
  5033. this._isIdentityDirty = true;
  5034. /**
  5035. * Gets or sets the internal data of the matrix
  5036. */
  5037. this.m = new Float32Array(16);
  5038. this._markAsUpdated();
  5039. }
  5040. /** @hidden */
  5041. Matrix.prototype._markAsUpdated = function () {
  5042. this.updateFlag = Matrix._updateFlagSeed++;
  5043. this._isIdentityDirty = true;
  5044. };
  5045. // Properties
  5046. /**
  5047. * Check if the current matrix is indentity
  5048. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5049. * @returns true is the matrix is the identity matrix
  5050. */
  5051. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5052. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5053. if (this._isIdentityDirty) {
  5054. this._isIdentityDirty = false;
  5055. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5056. this._isIdentity = false;
  5057. }
  5058. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5059. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5060. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5061. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5062. this._isIdentity = false;
  5063. }
  5064. else {
  5065. this._isIdentity = true;
  5066. }
  5067. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5068. this._isIdentity = false;
  5069. }
  5070. }
  5071. return this._isIdentity;
  5072. };
  5073. /**
  5074. * Gets the determinant of the matrix
  5075. * @returns the matrix determinant
  5076. */
  5077. Matrix.prototype.determinant = function () {
  5078. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5079. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5080. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5081. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5082. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5083. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5084. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5085. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5086. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5087. };
  5088. // Methods
  5089. /**
  5090. * Returns the matrix as a Float32Array
  5091. * @returns the matrix underlying array
  5092. */
  5093. Matrix.prototype.toArray = function () {
  5094. return this.m;
  5095. };
  5096. /**
  5097. * Returns the matrix as a Float32Array
  5098. * @returns the matrix underlying array.
  5099. */
  5100. Matrix.prototype.asArray = function () {
  5101. return this.toArray();
  5102. };
  5103. /**
  5104. * Inverts the current matrix in place
  5105. * @returns the current inverted matrix
  5106. */
  5107. Matrix.prototype.invert = function () {
  5108. this.invertToRef(this);
  5109. return this;
  5110. };
  5111. /**
  5112. * Sets all the matrix elements to zero
  5113. * @returns the current matrix
  5114. */
  5115. Matrix.prototype.reset = function () {
  5116. for (var index = 0; index < 16; index++) {
  5117. this.m[index] = 0.0;
  5118. }
  5119. this._markAsUpdated();
  5120. return this;
  5121. };
  5122. /**
  5123. * Adds the current matrix with a second one
  5124. * @param other defines the matrix to add
  5125. * @returns a new matrix as the addition of the current matrix and the given one
  5126. */
  5127. Matrix.prototype.add = function (other) {
  5128. var result = new Matrix();
  5129. this.addToRef(other, result);
  5130. return result;
  5131. };
  5132. /**
  5133. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5134. * @param other defines the matrix to add
  5135. * @param result defines the target matrix
  5136. * @returns the current matrix
  5137. */
  5138. Matrix.prototype.addToRef = function (other, result) {
  5139. for (var index = 0; index < 16; index++) {
  5140. result.m[index] = this.m[index] + other.m[index];
  5141. }
  5142. result._markAsUpdated();
  5143. return this;
  5144. };
  5145. /**
  5146. * Adds in place the given matrix to the current matrix
  5147. * @param other defines the second operand
  5148. * @returns the current updated matrix
  5149. */
  5150. Matrix.prototype.addToSelf = function (other) {
  5151. for (var index = 0; index < 16; index++) {
  5152. this.m[index] += other.m[index];
  5153. }
  5154. this._markAsUpdated();
  5155. return this;
  5156. };
  5157. /**
  5158. * Sets the given matrix to the current inverted Matrix
  5159. * @param other defines the target matrix
  5160. * @returns the unmodified current matrix
  5161. */
  5162. Matrix.prototype.invertToRef = function (other) {
  5163. var l1 = this.m[0];
  5164. var l2 = this.m[1];
  5165. var l3 = this.m[2];
  5166. var l4 = this.m[3];
  5167. var l5 = this.m[4];
  5168. var l6 = this.m[5];
  5169. var l7 = this.m[6];
  5170. var l8 = this.m[7];
  5171. var l9 = this.m[8];
  5172. var l10 = this.m[9];
  5173. var l11 = this.m[10];
  5174. var l12 = this.m[11];
  5175. var l13 = this.m[12];
  5176. var l14 = this.m[13];
  5177. var l15 = this.m[14];
  5178. var l16 = this.m[15];
  5179. var l17 = (l11 * l16) - (l12 * l15);
  5180. var l18 = (l10 * l16) - (l12 * l14);
  5181. var l19 = (l10 * l15) - (l11 * l14);
  5182. var l20 = (l9 * l16) - (l12 * l13);
  5183. var l21 = (l9 * l15) - (l11 * l13);
  5184. var l22 = (l9 * l14) - (l10 * l13);
  5185. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5186. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5187. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5188. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5189. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5190. var l28 = (l7 * l16) - (l8 * l15);
  5191. var l29 = (l6 * l16) - (l8 * l14);
  5192. var l30 = (l6 * l15) - (l7 * l14);
  5193. var l31 = (l5 * l16) - (l8 * l13);
  5194. var l32 = (l5 * l15) - (l7 * l13);
  5195. var l33 = (l5 * l14) - (l6 * l13);
  5196. var l34 = (l7 * l12) - (l8 * l11);
  5197. var l35 = (l6 * l12) - (l8 * l10);
  5198. var l36 = (l6 * l11) - (l7 * l10);
  5199. var l37 = (l5 * l12) - (l8 * l9);
  5200. var l38 = (l5 * l11) - (l7 * l9);
  5201. var l39 = (l5 * l10) - (l6 * l9);
  5202. other.m[0] = l23 * l27;
  5203. other.m[4] = l24 * l27;
  5204. other.m[8] = l25 * l27;
  5205. other.m[12] = l26 * l27;
  5206. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5207. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5208. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5209. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5210. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5211. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5212. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5213. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5214. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5215. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5216. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5217. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5218. other._markAsUpdated();
  5219. return this;
  5220. };
  5221. /**
  5222. * Inserts the translation vector (using 3 floats) in the current matrix
  5223. * @param x defines the 1st component of the translation
  5224. * @param y defines the 2nd component of the translation
  5225. * @param z defines the 3rd component of the translation
  5226. * @returns the current updated matrix
  5227. */
  5228. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5229. this.m[12] = x;
  5230. this.m[13] = y;
  5231. this.m[14] = z;
  5232. this._markAsUpdated();
  5233. return this;
  5234. };
  5235. /**
  5236. * Inserts the translation vector in the current matrix
  5237. * @param vector3 defines the translation to insert
  5238. * @returns the current updated matrix
  5239. */
  5240. Matrix.prototype.setTranslation = function (vector3) {
  5241. this.m[12] = vector3.x;
  5242. this.m[13] = vector3.y;
  5243. this.m[14] = vector3.z;
  5244. this._markAsUpdated();
  5245. return this;
  5246. };
  5247. /**
  5248. * Gets the translation value of the current matrix
  5249. * @returns a new Vector3 as the extracted translation from the matrix
  5250. */
  5251. Matrix.prototype.getTranslation = function () {
  5252. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5253. };
  5254. /**
  5255. * Fill a Vector3 with the extracted translation from the matrix
  5256. * @param result defines the Vector3 where to store the translation
  5257. * @returns the current matrix
  5258. */
  5259. Matrix.prototype.getTranslationToRef = function (result) {
  5260. result.x = this.m[12];
  5261. result.y = this.m[13];
  5262. result.z = this.m[14];
  5263. return this;
  5264. };
  5265. /**
  5266. * Remove rotation and scaling part from the matrix
  5267. * @returns the updated matrix
  5268. */
  5269. Matrix.prototype.removeRotationAndScaling = function () {
  5270. this.setRowFromFloats(0, 1, 0, 0, 0);
  5271. this.setRowFromFloats(1, 0, 1, 0, 0);
  5272. this.setRowFromFloats(2, 0, 0, 1, 0);
  5273. return this;
  5274. };
  5275. /**
  5276. * Multiply two matrices
  5277. * @param other defines the second operand
  5278. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5279. */
  5280. Matrix.prototype.multiply = function (other) {
  5281. var result = new Matrix();
  5282. this.multiplyToRef(other, result);
  5283. return result;
  5284. };
  5285. /**
  5286. * Copy the current matrix from the given one
  5287. * @param other defines the source matrix
  5288. * @returns the current updated matrix
  5289. */
  5290. Matrix.prototype.copyFrom = function (other) {
  5291. for (var index = 0; index < 16; index++) {
  5292. this.m[index] = other.m[index];
  5293. }
  5294. this._markAsUpdated();
  5295. return this;
  5296. };
  5297. /**
  5298. * Populates the given array from the starting index with the current matrix values
  5299. * @param array defines the target array
  5300. * @param offset defines the offset in the target array where to start storing values
  5301. * @returns the current matrix
  5302. */
  5303. Matrix.prototype.copyToArray = function (array, offset) {
  5304. if (offset === void 0) { offset = 0; }
  5305. for (var index = 0; index < 16; index++) {
  5306. array[offset + index] = this.m[index];
  5307. }
  5308. return this;
  5309. };
  5310. /**
  5311. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5312. * @param other defines the second operand
  5313. * @param result defines the matrix where to store the multiplication
  5314. * @returns the current matrix
  5315. */
  5316. Matrix.prototype.multiplyToRef = function (other, result) {
  5317. this.multiplyToArray(other, result.m, 0);
  5318. result._markAsUpdated();
  5319. return this;
  5320. };
  5321. /**
  5322. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5323. * @param other defines the second operand
  5324. * @param result defines the array where to store the multiplication
  5325. * @param offset defines the offset in the target array where to start storing values
  5326. * @returns the current matrix
  5327. */
  5328. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5329. var tm0 = this.m[0];
  5330. var tm1 = this.m[1];
  5331. var tm2 = this.m[2];
  5332. var tm3 = this.m[3];
  5333. var tm4 = this.m[4];
  5334. var tm5 = this.m[5];
  5335. var tm6 = this.m[6];
  5336. var tm7 = this.m[7];
  5337. var tm8 = this.m[8];
  5338. var tm9 = this.m[9];
  5339. var tm10 = this.m[10];
  5340. var tm11 = this.m[11];
  5341. var tm12 = this.m[12];
  5342. var tm13 = this.m[13];
  5343. var tm14 = this.m[14];
  5344. var tm15 = this.m[15];
  5345. var om0 = other.m[0];
  5346. var om1 = other.m[1];
  5347. var om2 = other.m[2];
  5348. var om3 = other.m[3];
  5349. var om4 = other.m[4];
  5350. var om5 = other.m[5];
  5351. var om6 = other.m[6];
  5352. var om7 = other.m[7];
  5353. var om8 = other.m[8];
  5354. var om9 = other.m[9];
  5355. var om10 = other.m[10];
  5356. var om11 = other.m[11];
  5357. var om12 = other.m[12];
  5358. var om13 = other.m[13];
  5359. var om14 = other.m[14];
  5360. var om15 = other.m[15];
  5361. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5362. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5363. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5364. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5365. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5366. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5367. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5368. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5369. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5370. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5371. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5372. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5373. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5374. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5375. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5376. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5377. return this;
  5378. };
  5379. /**
  5380. * Check equality between this matrix and a second one
  5381. * @param value defines the second matrix to compare
  5382. * @returns true is the current matrix and the given one values are strictly equal
  5383. */
  5384. Matrix.prototype.equals = function (value) {
  5385. return value &&
  5386. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5387. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5388. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5389. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5390. };
  5391. /**
  5392. * Clone the current matrix
  5393. * @returns a new matrix from the current matrix
  5394. */
  5395. Matrix.prototype.clone = function () {
  5396. 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]);
  5397. };
  5398. /**
  5399. * Returns the name of the current matrix class
  5400. * @returns the string "Matrix"
  5401. */
  5402. Matrix.prototype.getClassName = function () {
  5403. return "Matrix";
  5404. };
  5405. /**
  5406. * Gets the hash code of the current matrix
  5407. * @returns the hash code
  5408. */
  5409. Matrix.prototype.getHashCode = function () {
  5410. var hash = this.m[0] || 0;
  5411. for (var i = 1; i < 16; i++) {
  5412. hash = (hash * 397) ^ (this.m[i] || 0);
  5413. }
  5414. return hash;
  5415. };
  5416. /**
  5417. * Decomposes the current Matrix into a translation, rotation and scaling components
  5418. * @param scale defines the scale vector3 given as a reference to update
  5419. * @param rotation defines the rotation quaternion given as a reference to update
  5420. * @param translation defines the translation vector3 given as a reference to update
  5421. * @returns true if operation was successful
  5422. */
  5423. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5424. if (translation) {
  5425. translation.x = this.m[12];
  5426. translation.y = this.m[13];
  5427. translation.z = this.m[14];
  5428. }
  5429. scale = scale || MathTmp.Vector3[0];
  5430. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5431. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5432. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5433. if (this.determinant() <= 0) {
  5434. scale.y *= -1;
  5435. }
  5436. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5437. if (rotation) {
  5438. rotation.x = 0;
  5439. rotation.y = 0;
  5440. rotation.z = 0;
  5441. rotation.w = 1;
  5442. }
  5443. return false;
  5444. }
  5445. if (rotation) {
  5446. 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]);
  5447. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5448. }
  5449. return true;
  5450. };
  5451. /**
  5452. * Gets specific row of the matrix
  5453. * @param index defines the number of the row to get
  5454. * @returns the index-th row of the current matrix as a new Vector4
  5455. */
  5456. Matrix.prototype.getRow = function (index) {
  5457. if (index < 0 || index > 3) {
  5458. return null;
  5459. }
  5460. var i = index * 4;
  5461. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5462. };
  5463. /**
  5464. * Sets the index-th row of the current matrix to the vector4 values
  5465. * @param index defines the number of the row to set
  5466. * @param row defines the target vector4
  5467. * @returns the updated current matrix
  5468. */
  5469. Matrix.prototype.setRow = function (index, row) {
  5470. if (index < 0 || index > 3) {
  5471. return this;
  5472. }
  5473. var i = index * 4;
  5474. this.m[i + 0] = row.x;
  5475. this.m[i + 1] = row.y;
  5476. this.m[i + 2] = row.z;
  5477. this.m[i + 3] = row.w;
  5478. this._markAsUpdated();
  5479. return this;
  5480. };
  5481. /**
  5482. * Compute the transpose of the matrix
  5483. * @returns the new transposed matrix
  5484. */
  5485. Matrix.prototype.transpose = function () {
  5486. return Matrix.Transpose(this);
  5487. };
  5488. /**
  5489. * Compute the transpose of the matrix and store it in a given matrix
  5490. * @param result defines the target matrix
  5491. * @returns the current matrix
  5492. */
  5493. Matrix.prototype.transposeToRef = function (result) {
  5494. Matrix.TransposeToRef(this, result);
  5495. return this;
  5496. };
  5497. /**
  5498. * Sets the index-th row of the current matrix with the given 4 x float values
  5499. * @param index defines the row index
  5500. * @param x defines the x component to set
  5501. * @param y defines the y component to set
  5502. * @param z defines the z component to set
  5503. * @param w defines the w component to set
  5504. * @returns the updated current matrix
  5505. */
  5506. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5507. if (index < 0 || index > 3) {
  5508. return this;
  5509. }
  5510. var i = index * 4;
  5511. this.m[i + 0] = x;
  5512. this.m[i + 1] = y;
  5513. this.m[i + 2] = z;
  5514. this.m[i + 3] = w;
  5515. this._markAsUpdated();
  5516. return this;
  5517. };
  5518. /**
  5519. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5520. * @param scale defines the scale factor
  5521. * @returns a new matrix
  5522. */
  5523. Matrix.prototype.scale = function (scale) {
  5524. var result = new Matrix();
  5525. this.scaleToRef(scale, result);
  5526. return result;
  5527. };
  5528. /**
  5529. * Scale the current matrix values by a factor to a given result matrix
  5530. * @param scale defines the scale factor
  5531. * @param result defines the matrix to store the result
  5532. * @returns the current matrix
  5533. */
  5534. Matrix.prototype.scaleToRef = function (scale, result) {
  5535. for (var index = 0; index < 16; index++) {
  5536. result.m[index] = this.m[index] * scale;
  5537. }
  5538. result._markAsUpdated();
  5539. return this;
  5540. };
  5541. /**
  5542. * Scale the current matrix values by a factor and add the result to a given matrix
  5543. * @param scale defines the scale factor
  5544. * @param result defines the Matrix to store the result
  5545. * @returns the current matrix
  5546. */
  5547. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5548. for (var index = 0; index < 16; index++) {
  5549. result.m[index] += this.m[index] * scale;
  5550. }
  5551. result._markAsUpdated();
  5552. return this;
  5553. };
  5554. /**
  5555. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5556. * @param ref matrix to store the result
  5557. */
  5558. Matrix.prototype.toNormalMatrix = function (ref) {
  5559. this.invertToRef(ref);
  5560. ref.transpose();
  5561. var m = ref.m;
  5562. 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);
  5563. };
  5564. /**
  5565. * Gets only rotation part of the current matrix
  5566. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5567. */
  5568. Matrix.prototype.getRotationMatrix = function () {
  5569. var result = Matrix.Identity();
  5570. this.getRotationMatrixToRef(result);
  5571. return result;
  5572. };
  5573. /**
  5574. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5575. * @param result defines the target matrix to store data to
  5576. * @returns the current matrix
  5577. */
  5578. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5579. var m = this.m;
  5580. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5581. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5582. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5583. if (this.determinant() <= 0) {
  5584. sy *= -1;
  5585. }
  5586. if (sx === 0 || sy === 0 || sz === 0) {
  5587. Matrix.IdentityToRef(result);
  5588. }
  5589. else {
  5590. 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);
  5591. }
  5592. return this;
  5593. };
  5594. // Statics
  5595. /**
  5596. * Creates a matrix from an array
  5597. * @param array defines the source array
  5598. * @param offset defines an offset in the source array
  5599. * @returns a new Matrix set from the starting index of the given array
  5600. */
  5601. Matrix.FromArray = function (array, offset) {
  5602. var result = new Matrix();
  5603. if (!offset) {
  5604. offset = 0;
  5605. }
  5606. Matrix.FromArrayToRef(array, offset, result);
  5607. return result;
  5608. };
  5609. /**
  5610. * Copy the content of an array into a given matrix
  5611. * @param array defines the source array
  5612. * @param offset defines an offset in the source array
  5613. * @param result defines the target matrix
  5614. */
  5615. Matrix.FromArrayToRef = function (array, offset, result) {
  5616. for (var index = 0; index < 16; index++) {
  5617. result.m[index] = array[index + offset];
  5618. }
  5619. result._markAsUpdated();
  5620. };
  5621. /**
  5622. * Stores an array into a matrix after having multiplied each component by a given factor
  5623. * @param array defines the source array
  5624. * @param offset defines the offset in the source array
  5625. * @param scale defines the scaling factor
  5626. * @param result defines the target matrix
  5627. */
  5628. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5629. for (var index = 0; index < 16; index++) {
  5630. result.m[index] = array[index + offset] * scale;
  5631. }
  5632. result._markAsUpdated();
  5633. };
  5634. /**
  5635. * Stores a list of values (16) inside a given matrix
  5636. * @param initialM11 defines 1st value of 1st row
  5637. * @param initialM12 defines 2nd value of 1st row
  5638. * @param initialM13 defines 3rd value of 1st row
  5639. * @param initialM14 defines 4th value of 1st row
  5640. * @param initialM21 defines 1st value of 2nd row
  5641. * @param initialM22 defines 2nd value of 2nd row
  5642. * @param initialM23 defines 3rd value of 2nd row
  5643. * @param initialM24 defines 4th value of 2nd row
  5644. * @param initialM31 defines 1st value of 3rd row
  5645. * @param initialM32 defines 2nd value of 3rd row
  5646. * @param initialM33 defines 3rd value of 3rd row
  5647. * @param initialM34 defines 4th value of 3rd row
  5648. * @param initialM41 defines 1st value of 4th row
  5649. * @param initialM42 defines 2nd value of 4th row
  5650. * @param initialM43 defines 3rd value of 4th row
  5651. * @param initialM44 defines 4th value of 4th row
  5652. * @param result defines the target matrix
  5653. */
  5654. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5655. result.m[0] = initialM11;
  5656. result.m[1] = initialM12;
  5657. result.m[2] = initialM13;
  5658. result.m[3] = initialM14;
  5659. result.m[4] = initialM21;
  5660. result.m[5] = initialM22;
  5661. result.m[6] = initialM23;
  5662. result.m[7] = initialM24;
  5663. result.m[8] = initialM31;
  5664. result.m[9] = initialM32;
  5665. result.m[10] = initialM33;
  5666. result.m[11] = initialM34;
  5667. result.m[12] = initialM41;
  5668. result.m[13] = initialM42;
  5669. result.m[14] = initialM43;
  5670. result.m[15] = initialM44;
  5671. result._markAsUpdated();
  5672. };
  5673. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5674. /**
  5675. * Gets an identity matrix that must not be updated
  5676. */
  5677. get: function () {
  5678. return Matrix._identityReadOnly;
  5679. },
  5680. enumerable: true,
  5681. configurable: true
  5682. });
  5683. /**
  5684. * Creates new matrix from a list of values (16)
  5685. * @param initialM11 defines 1st value of 1st row
  5686. * @param initialM12 defines 2nd value of 1st row
  5687. * @param initialM13 defines 3rd value of 1st row
  5688. * @param initialM14 defines 4th value of 1st row
  5689. * @param initialM21 defines 1st value of 2nd row
  5690. * @param initialM22 defines 2nd value of 2nd row
  5691. * @param initialM23 defines 3rd value of 2nd row
  5692. * @param initialM24 defines 4th value of 2nd row
  5693. * @param initialM31 defines 1st value of 3rd row
  5694. * @param initialM32 defines 2nd value of 3rd row
  5695. * @param initialM33 defines 3rd value of 3rd row
  5696. * @param initialM34 defines 4th value of 3rd row
  5697. * @param initialM41 defines 1st value of 4th row
  5698. * @param initialM42 defines 2nd value of 4th row
  5699. * @param initialM43 defines 3rd value of 4th row
  5700. * @param initialM44 defines 4th value of 4th row
  5701. * @returns the new matrix
  5702. */
  5703. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5704. var result = new Matrix();
  5705. result.m[0] = initialM11;
  5706. result.m[1] = initialM12;
  5707. result.m[2] = initialM13;
  5708. result.m[3] = initialM14;
  5709. result.m[4] = initialM21;
  5710. result.m[5] = initialM22;
  5711. result.m[6] = initialM23;
  5712. result.m[7] = initialM24;
  5713. result.m[8] = initialM31;
  5714. result.m[9] = initialM32;
  5715. result.m[10] = initialM33;
  5716. result.m[11] = initialM34;
  5717. result.m[12] = initialM41;
  5718. result.m[13] = initialM42;
  5719. result.m[14] = initialM43;
  5720. result.m[15] = initialM44;
  5721. return result;
  5722. };
  5723. /**
  5724. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5725. * @param scale defines the scale vector3
  5726. * @param rotation defines the rotation quaternion
  5727. * @param translation defines the translation vector3
  5728. * @returns a new matrix
  5729. */
  5730. Matrix.Compose = function (scale, rotation, translation) {
  5731. var result = Matrix.Identity();
  5732. Matrix.ComposeToRef(scale, rotation, translation, result);
  5733. return result;
  5734. };
  5735. /**
  5736. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5737. * @param scale defines the scale vector3
  5738. * @param rotation defines the rotation quaternion
  5739. * @param translation defines the translation vector3
  5740. * @param result defines the target matrix
  5741. */
  5742. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5743. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5744. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5745. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5746. result.setTranslation(translation);
  5747. };
  5748. /**
  5749. * Creates a new identity matrix
  5750. * @returns a new identity matrix
  5751. */
  5752. Matrix.Identity = function () {
  5753. 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);
  5754. };
  5755. /**
  5756. * Creates a new identity matrix and stores the result in a given matrix
  5757. * @param result defines the target matrix
  5758. */
  5759. Matrix.IdentityToRef = function (result) {
  5760. 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);
  5761. };
  5762. /**
  5763. * Creates a new zero matrix
  5764. * @returns a new zero matrix
  5765. */
  5766. Matrix.Zero = function () {
  5767. 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);
  5768. };
  5769. /**
  5770. * Creates a new rotation matrix for "angle" radians around the X axis
  5771. * @param angle defines the angle (in radians) to use
  5772. * @return the new matrix
  5773. */
  5774. Matrix.RotationX = function (angle) {
  5775. var result = new Matrix();
  5776. Matrix.RotationXToRef(angle, result);
  5777. return result;
  5778. };
  5779. /**
  5780. * Creates a new matrix as the invert of a given matrix
  5781. * @param source defines the source matrix
  5782. * @returns the new matrix
  5783. */
  5784. Matrix.Invert = function (source) {
  5785. var result = new Matrix();
  5786. source.invertToRef(result);
  5787. return result;
  5788. };
  5789. /**
  5790. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5791. * @param angle defines the angle (in radians) to use
  5792. * @param result defines the target matrix
  5793. */
  5794. Matrix.RotationXToRef = function (angle, result) {
  5795. var s = Math.sin(angle);
  5796. var c = Math.cos(angle);
  5797. result.m[0] = 1.0;
  5798. result.m[15] = 1.0;
  5799. result.m[5] = c;
  5800. result.m[10] = c;
  5801. result.m[9] = -s;
  5802. result.m[6] = s;
  5803. result.m[1] = 0.0;
  5804. result.m[2] = 0.0;
  5805. result.m[3] = 0.0;
  5806. result.m[4] = 0.0;
  5807. result.m[7] = 0.0;
  5808. result.m[8] = 0.0;
  5809. result.m[11] = 0.0;
  5810. result.m[12] = 0.0;
  5811. result.m[13] = 0.0;
  5812. result.m[14] = 0.0;
  5813. result._markAsUpdated();
  5814. };
  5815. /**
  5816. * Creates a new rotation matrix for "angle" radians around the Y axis
  5817. * @param angle defines the angle (in radians) to use
  5818. * @return the new matrix
  5819. */
  5820. Matrix.RotationY = function (angle) {
  5821. var result = new Matrix();
  5822. Matrix.RotationYToRef(angle, result);
  5823. return result;
  5824. };
  5825. /**
  5826. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5827. * @param angle defines the angle (in radians) to use
  5828. * @param result defines the target matrix
  5829. */
  5830. Matrix.RotationYToRef = function (angle, result) {
  5831. var s = Math.sin(angle);
  5832. var c = Math.cos(angle);
  5833. result.m[5] = 1.0;
  5834. result.m[15] = 1.0;
  5835. result.m[0] = c;
  5836. result.m[2] = -s;
  5837. result.m[8] = s;
  5838. result.m[10] = c;
  5839. result.m[1] = 0.0;
  5840. result.m[3] = 0.0;
  5841. result.m[4] = 0.0;
  5842. result.m[6] = 0.0;
  5843. result.m[7] = 0.0;
  5844. result.m[9] = 0.0;
  5845. result.m[11] = 0.0;
  5846. result.m[12] = 0.0;
  5847. result.m[13] = 0.0;
  5848. result.m[14] = 0.0;
  5849. result._markAsUpdated();
  5850. };
  5851. /**
  5852. * Creates a new rotation matrix for "angle" radians around the Z axis
  5853. * @param angle defines the angle (in radians) to use
  5854. * @return the new matrix
  5855. */
  5856. Matrix.RotationZ = function (angle) {
  5857. var result = new Matrix();
  5858. Matrix.RotationZToRef(angle, result);
  5859. return result;
  5860. };
  5861. /**
  5862. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5863. * @param angle defines the angle (in radians) to use
  5864. * @param result defines the target matrix
  5865. */
  5866. Matrix.RotationZToRef = function (angle, result) {
  5867. var s = Math.sin(angle);
  5868. var c = Math.cos(angle);
  5869. result.m[10] = 1.0;
  5870. result.m[15] = 1.0;
  5871. result.m[0] = c;
  5872. result.m[1] = s;
  5873. result.m[4] = -s;
  5874. result.m[5] = c;
  5875. result.m[2] = 0.0;
  5876. result.m[3] = 0.0;
  5877. result.m[6] = 0.0;
  5878. result.m[7] = 0.0;
  5879. result.m[8] = 0.0;
  5880. result.m[9] = 0.0;
  5881. result.m[11] = 0.0;
  5882. result.m[12] = 0.0;
  5883. result.m[13] = 0.0;
  5884. result.m[14] = 0.0;
  5885. result._markAsUpdated();
  5886. };
  5887. /**
  5888. * Creates a new rotation matrix for "angle" radians around the given axis
  5889. * @param axis defines the axis to use
  5890. * @param angle defines the angle (in radians) to use
  5891. * @return the new matrix
  5892. */
  5893. Matrix.RotationAxis = function (axis, angle) {
  5894. var result = Matrix.Zero();
  5895. Matrix.RotationAxisToRef(axis, angle, result);
  5896. return result;
  5897. };
  5898. /**
  5899. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5900. * @param axis defines the axis to use
  5901. * @param angle defines the angle (in radians) to use
  5902. * @param result defines the target matrix
  5903. */
  5904. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5905. var s = Math.sin(-angle);
  5906. var c = Math.cos(-angle);
  5907. var c1 = 1 - c;
  5908. axis.normalize();
  5909. result.m[0] = (axis.x * axis.x) * c1 + c;
  5910. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5911. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5912. result.m[3] = 0.0;
  5913. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5914. result.m[5] = (axis.y * axis.y) * c1 + c;
  5915. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5916. result.m[7] = 0.0;
  5917. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5918. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5919. result.m[10] = (axis.z * axis.z) * c1 + c;
  5920. result.m[11] = 0.0;
  5921. result.m[15] = 1.0;
  5922. result._markAsUpdated();
  5923. };
  5924. /**
  5925. * Creates a rotation matrix
  5926. * @param yaw defines the yaw angle in radians (Y axis)
  5927. * @param pitch defines the pitch angle in radians (X axis)
  5928. * @param roll defines the roll angle in radians (X axis)
  5929. * @returns the new rotation matrix
  5930. */
  5931. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5932. var result = new Matrix();
  5933. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5934. return result;
  5935. };
  5936. /**
  5937. * Creates a rotation matrix and stores it in a given matrix
  5938. * @param yaw defines the yaw angle in radians (Y axis)
  5939. * @param pitch defines the pitch angle in radians (X axis)
  5940. * @param roll defines the roll angle in radians (X axis)
  5941. * @param result defines the target matrix
  5942. */
  5943. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5944. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5945. this._tempQuaternion.toRotationMatrix(result);
  5946. };
  5947. /**
  5948. * Creates a scaling matrix
  5949. * @param x defines the scale factor on X axis
  5950. * @param y defines the scale factor on Y axis
  5951. * @param z defines the scale factor on Z axis
  5952. * @returns the new matrix
  5953. */
  5954. Matrix.Scaling = function (x, y, z) {
  5955. var result = Matrix.Zero();
  5956. Matrix.ScalingToRef(x, y, z, result);
  5957. return result;
  5958. };
  5959. /**
  5960. * Creates a scaling matrix and stores it in a given matrix
  5961. * @param x defines the scale factor on X axis
  5962. * @param y defines the scale factor on Y axis
  5963. * @param z defines the scale factor on Z axis
  5964. * @param result defines the target matrix
  5965. */
  5966. Matrix.ScalingToRef = function (x, y, z, result) {
  5967. result.m[0] = x;
  5968. result.m[1] = 0.0;
  5969. result.m[2] = 0.0;
  5970. result.m[3] = 0.0;
  5971. result.m[4] = 0.0;
  5972. result.m[5] = y;
  5973. result.m[6] = 0.0;
  5974. result.m[7] = 0.0;
  5975. result.m[8] = 0.0;
  5976. result.m[9] = 0.0;
  5977. result.m[10] = z;
  5978. result.m[11] = 0.0;
  5979. result.m[12] = 0.0;
  5980. result.m[13] = 0.0;
  5981. result.m[14] = 0.0;
  5982. result.m[15] = 1.0;
  5983. result._markAsUpdated();
  5984. };
  5985. /**
  5986. * Creates a translation matrix
  5987. * @param x defines the translation on X axis
  5988. * @param y defines the translation on Y axis
  5989. * @param z defines the translationon Z axis
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Translation = function (x, y, z) {
  5993. var result = Matrix.Identity();
  5994. Matrix.TranslationToRef(x, y, z, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Creates a translation matrix and stores it in a given matrix
  5999. * @param x defines the translation on X axis
  6000. * @param y defines the translation on Y axis
  6001. * @param z defines the translationon Z axis
  6002. * @param result defines the target matrix
  6003. */
  6004. Matrix.TranslationToRef = function (x, y, z, result) {
  6005. 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);
  6006. };
  6007. /**
  6008. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6009. * @param startValue defines the start value
  6010. * @param endValue defines the end value
  6011. * @param gradient defines the gradient factor
  6012. * @returns the new matrix
  6013. */
  6014. Matrix.Lerp = function (startValue, endValue, gradient) {
  6015. var result = Matrix.Zero();
  6016. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6017. return result;
  6018. };
  6019. /**
  6020. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6021. * @param startValue defines the start value
  6022. * @param endValue defines the end value
  6023. * @param gradient defines the gradient factor
  6024. * @param result defines the Matrix object where to store data
  6025. */
  6026. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6027. for (var index = 0; index < 16; index++) {
  6028. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6029. }
  6030. result._markAsUpdated();
  6031. };
  6032. /**
  6033. * Builds a new matrix whose values are computed by:
  6034. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6035. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6036. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6037. * @param startValue defines the first matrix
  6038. * @param endValue defines the second matrix
  6039. * @param gradient defines the gradient between the two matrices
  6040. * @returns the new matrix
  6041. */
  6042. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6043. var result = Matrix.Zero();
  6044. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6045. return result;
  6046. };
  6047. /**
  6048. * Update a matrix to values which are computed by:
  6049. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6050. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6051. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6052. * @param startValue defines the first matrix
  6053. * @param endValue defines the second matrix
  6054. * @param gradient defines the gradient between the two matrices
  6055. * @param result defines the target matrix
  6056. */
  6057. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6058. var startScale = MathTmp.Vector3[0];
  6059. var startRotation = MathTmp.Quaternion[0];
  6060. var startTranslation = MathTmp.Vector3[1];
  6061. startValue.decompose(startScale, startRotation, startTranslation);
  6062. var endScale = MathTmp.Vector3[2];
  6063. var endRotation = MathTmp.Quaternion[1];
  6064. var endTranslation = MathTmp.Vector3[3];
  6065. endValue.decompose(endScale, endRotation, endTranslation);
  6066. var resultScale = MathTmp.Vector3[4];
  6067. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6068. var resultRotation = MathTmp.Quaternion[2];
  6069. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6070. var resultTranslation = MathTmp.Vector3[5];
  6071. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6072. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6073. };
  6074. /**
  6075. * 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"
  6076. * This function works in left handed mode
  6077. * @param eye defines the final position of the entity
  6078. * @param target defines where the entity should look at
  6079. * @param up defines the up vector for the entity
  6080. * @returns the new matrix
  6081. */
  6082. Matrix.LookAtLH = function (eye, target, up) {
  6083. var result = Matrix.Zero();
  6084. Matrix.LookAtLHToRef(eye, target, up, result);
  6085. return result;
  6086. };
  6087. /**
  6088. * 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".
  6089. * This function works in left handed mode
  6090. * @param eye defines the final position of the entity
  6091. * @param target defines where the entity should look at
  6092. * @param up defines the up vector for the entity
  6093. * @param result defines the target matrix
  6094. */
  6095. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6096. // Z axis
  6097. target.subtractToRef(eye, this._zAxis);
  6098. this._zAxis.normalize();
  6099. // X axis
  6100. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6101. if (this._xAxis.lengthSquared() === 0) {
  6102. this._xAxis.x = 1.0;
  6103. }
  6104. else {
  6105. this._xAxis.normalize();
  6106. }
  6107. // Y axis
  6108. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6109. this._yAxis.normalize();
  6110. // Eye angles
  6111. var ex = -Vector3.Dot(this._xAxis, eye);
  6112. var ey = -Vector3.Dot(this._yAxis, eye);
  6113. var ez = -Vector3.Dot(this._zAxis, eye);
  6114. 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);
  6115. };
  6116. /**
  6117. * 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"
  6118. * This function works in right handed mode
  6119. * @param eye defines the final position of the entity
  6120. * @param target defines where the entity should look at
  6121. * @param up defines the up vector for the entity
  6122. * @returns the new matrix
  6123. */
  6124. Matrix.LookAtRH = function (eye, target, up) {
  6125. var result = Matrix.Zero();
  6126. Matrix.LookAtRHToRef(eye, target, up, result);
  6127. return result;
  6128. };
  6129. /**
  6130. * 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".
  6131. * This function works in right handed mode
  6132. * @param eye defines the final position of the entity
  6133. * @param target defines where the entity should look at
  6134. * @param up defines the up vector for the entity
  6135. * @param result defines the target matrix
  6136. */
  6137. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6138. // Z axis
  6139. eye.subtractToRef(target, this._zAxis);
  6140. this._zAxis.normalize();
  6141. // X axis
  6142. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6143. if (this._xAxis.lengthSquared() === 0) {
  6144. this._xAxis.x = 1.0;
  6145. }
  6146. else {
  6147. this._xAxis.normalize();
  6148. }
  6149. // Y axis
  6150. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6151. this._yAxis.normalize();
  6152. // Eye angles
  6153. var ex = -Vector3.Dot(this._xAxis, eye);
  6154. var ey = -Vector3.Dot(this._yAxis, eye);
  6155. var ez = -Vector3.Dot(this._zAxis, eye);
  6156. 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);
  6157. };
  6158. /**
  6159. * Create a left-handed orthographic projection matrix
  6160. * @param width defines the viewport width
  6161. * @param height defines the viewport height
  6162. * @param znear defines the near clip plane
  6163. * @param zfar defines the far clip plane
  6164. * @returns a new matrix as a left-handed orthographic projection matrix
  6165. */
  6166. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6167. var matrix = Matrix.Zero();
  6168. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6169. return matrix;
  6170. };
  6171. /**
  6172. * Store a left-handed orthographic projection to a given matrix
  6173. * @param width defines the viewport width
  6174. * @param height defines the viewport height
  6175. * @param znear defines the near clip plane
  6176. * @param zfar defines the far clip plane
  6177. * @param result defines the target matrix
  6178. */
  6179. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6180. var n = znear;
  6181. var f = zfar;
  6182. var a = 2.0 / width;
  6183. var b = 2.0 / height;
  6184. var c = 2.0 / (f - n);
  6185. var d = -(f + n) / (f - n);
  6186. 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);
  6187. };
  6188. /**
  6189. * Create a left-handed orthographic projection matrix
  6190. * @param left defines the viewport left coordinate
  6191. * @param right defines the viewport right coordinate
  6192. * @param bottom defines the viewport bottom coordinate
  6193. * @param top defines the viewport top coordinate
  6194. * @param znear defines the near clip plane
  6195. * @param zfar defines the far clip plane
  6196. * @returns a new matrix as a left-handed orthographic projection matrix
  6197. */
  6198. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6199. var matrix = Matrix.Zero();
  6200. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6201. return matrix;
  6202. };
  6203. /**
  6204. * Stores a left-handed orthographic projection into a given matrix
  6205. * @param left defines the viewport left coordinate
  6206. * @param right defines the viewport right coordinate
  6207. * @param bottom defines the viewport bottom coordinate
  6208. * @param top defines the viewport top coordinate
  6209. * @param znear defines the near clip plane
  6210. * @param zfar defines the far clip plane
  6211. * @param result defines the target matrix
  6212. */
  6213. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6214. var n = znear;
  6215. var f = zfar;
  6216. var a = 2.0 / (right - left);
  6217. var b = 2.0 / (top - bottom);
  6218. var c = 2.0 / (f - n);
  6219. var d = -(f + n) / (f - n);
  6220. var i0 = (left + right) / (left - right);
  6221. var i1 = (top + bottom) / (bottom - top);
  6222. 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);
  6223. };
  6224. /**
  6225. * Creates a right-handed orthographic projection matrix
  6226. * @param left defines the viewport left coordinate
  6227. * @param right defines the viewport right coordinate
  6228. * @param bottom defines the viewport bottom coordinate
  6229. * @param top defines the viewport top coordinate
  6230. * @param znear defines the near clip plane
  6231. * @param zfar defines the far clip plane
  6232. * @returns a new matrix as a right-handed orthographic projection matrix
  6233. */
  6234. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6235. var matrix = Matrix.Zero();
  6236. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6237. return matrix;
  6238. };
  6239. /**
  6240. * Stores a right-handed orthographic projection into a given matrix
  6241. * @param left defines the viewport left coordinate
  6242. * @param right defines the viewport right coordinate
  6243. * @param bottom defines the viewport bottom coordinate
  6244. * @param top defines the viewport top coordinate
  6245. * @param znear defines the near clip plane
  6246. * @param zfar defines the far clip plane
  6247. * @param result defines the target matrix
  6248. */
  6249. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6250. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6251. result.m[10] *= -1.0;
  6252. };
  6253. /**
  6254. * Creates a left-handed perspective projection matrix
  6255. * @param width defines the viewport width
  6256. * @param height defines the viewport height
  6257. * @param znear defines the near clip plane
  6258. * @param zfar defines the far clip plane
  6259. * @returns a new matrix as a left-handed perspective projection matrix
  6260. */
  6261. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6262. var matrix = Matrix.Zero();
  6263. var n = znear;
  6264. var f = zfar;
  6265. var a = 2.0 * n / width;
  6266. var b = 2.0 * n / height;
  6267. var c = (f + n) / (f - n);
  6268. var d = -2.0 * f * n / (f - n);
  6269. 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);
  6270. return matrix;
  6271. };
  6272. /**
  6273. * Creates a left-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 left-handed perspective projection matrix
  6279. */
  6280. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6281. var matrix = Matrix.Zero();
  6282. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6283. return matrix;
  6284. };
  6285. /**
  6286. * Stores a left-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.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6295. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6296. var n = znear;
  6297. var f = zfar;
  6298. var t = 1.0 / (Math.tan(fov * 0.5));
  6299. var a = isVerticalFovFixed ? (t / aspect) : t;
  6300. var b = isVerticalFovFixed ? t : (t * aspect);
  6301. var c = (f + n) / (f - n);
  6302. var d = -2.0 * f * n / (f - n);
  6303. 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);
  6304. };
  6305. /**
  6306. * Creates a right-handed perspective projection matrix
  6307. * @param fov defines the horizontal field of view
  6308. * @param aspect defines the aspect ratio
  6309. * @param znear defines the near clip plane
  6310. * @param zfar defines the far clip plane
  6311. * @returns a new matrix as a right-handed perspective projection matrix
  6312. */
  6313. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6314. var matrix = Matrix.Zero();
  6315. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6316. return matrix;
  6317. };
  6318. /**
  6319. * Stores a right-handed perspective projection into a given matrix
  6320. * @param fov defines the horizontal field of view
  6321. * @param aspect defines the aspect ratio
  6322. * @param znear defines the near clip plane
  6323. * @param zfar defines the far clip plane
  6324. * @param result defines the target matrix
  6325. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6326. */
  6327. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6328. //alternatively this could be expressed as:
  6329. // m = PerspectiveFovLHToRef
  6330. // m[10] *= -1.0;
  6331. // m[11] *= -1.0;
  6332. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6333. var n = znear;
  6334. var f = zfar;
  6335. var t = 1.0 / (Math.tan(fov * 0.5));
  6336. var a = isVerticalFovFixed ? (t / aspect) : t;
  6337. var b = isVerticalFovFixed ? t : (t * aspect);
  6338. var c = -(f + n) / (f - n);
  6339. var d = -2 * f * n / (f - n);
  6340. 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);
  6341. };
  6342. /**
  6343. * Stores a perspective projection for WebVR info a given matrix
  6344. * @param fov defines the field of view
  6345. * @param znear defines the near clip plane
  6346. * @param zfar defines the far clip plane
  6347. * @param result defines the target matrix
  6348. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6349. */
  6350. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6351. if (rightHanded === void 0) { rightHanded = false; }
  6352. var rightHandedFactor = rightHanded ? -1 : 1;
  6353. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6354. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6355. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6356. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6357. var xScale = 2.0 / (leftTan + rightTan);
  6358. var yScale = 2.0 / (upTan + downTan);
  6359. result.m[0] = xScale;
  6360. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6361. result.m[5] = yScale;
  6362. result.m[6] = result.m[7] = 0.0;
  6363. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6364. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6365. result.m[10] = -zfar / (znear - zfar);
  6366. result.m[11] = 1.0 * rightHandedFactor;
  6367. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6368. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6369. result._markAsUpdated();
  6370. };
  6371. /**
  6372. * Computes a complete transformation matrix
  6373. * @param viewport defines the viewport to use
  6374. * @param world defines the world matrix
  6375. * @param view defines the view matrix
  6376. * @param projection defines the projection matrix
  6377. * @param zmin defines the near clip plane
  6378. * @param zmax defines the far clip plane
  6379. * @returns the transformation matrix
  6380. */
  6381. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6382. var cw = viewport.width;
  6383. var ch = viewport.height;
  6384. var cx = viewport.x;
  6385. var cy = viewport.y;
  6386. 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);
  6387. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6388. };
  6389. /**
  6390. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6391. * @param matrix defines the matrix to use
  6392. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6393. */
  6394. Matrix.GetAsMatrix2x2 = function (matrix) {
  6395. return new Float32Array([
  6396. matrix.m[0], matrix.m[1],
  6397. matrix.m[4], matrix.m[5]
  6398. ]);
  6399. };
  6400. /**
  6401. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6402. * @param matrix defines the matrix to use
  6403. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6404. */
  6405. Matrix.GetAsMatrix3x3 = function (matrix) {
  6406. return new Float32Array([
  6407. matrix.m[0], matrix.m[1], matrix.m[2],
  6408. matrix.m[4], matrix.m[5], matrix.m[6],
  6409. matrix.m[8], matrix.m[9], matrix.m[10]
  6410. ]);
  6411. };
  6412. /**
  6413. * Compute the transpose of a given matrix
  6414. * @param matrix defines the matrix to transpose
  6415. * @returns the new matrix
  6416. */
  6417. Matrix.Transpose = function (matrix) {
  6418. var result = new Matrix();
  6419. Matrix.TransposeToRef(matrix, result);
  6420. return result;
  6421. };
  6422. /**
  6423. * Compute the transpose of a matrix and store it in a target matrix
  6424. * @param matrix defines the matrix to transpose
  6425. * @param result defines the target matrix
  6426. */
  6427. Matrix.TransposeToRef = function (matrix, result) {
  6428. result.m[0] = matrix.m[0];
  6429. result.m[1] = matrix.m[4];
  6430. result.m[2] = matrix.m[8];
  6431. result.m[3] = matrix.m[12];
  6432. result.m[4] = matrix.m[1];
  6433. result.m[5] = matrix.m[5];
  6434. result.m[6] = matrix.m[9];
  6435. result.m[7] = matrix.m[13];
  6436. result.m[8] = matrix.m[2];
  6437. result.m[9] = matrix.m[6];
  6438. result.m[10] = matrix.m[10];
  6439. result.m[11] = matrix.m[14];
  6440. result.m[12] = matrix.m[3];
  6441. result.m[13] = matrix.m[7];
  6442. result.m[14] = matrix.m[11];
  6443. result.m[15] = matrix.m[15];
  6444. };
  6445. /**
  6446. * Computes a reflection matrix from a plane
  6447. * @param plane defines the reflection plane
  6448. * @returns a new matrix
  6449. */
  6450. Matrix.Reflection = function (plane) {
  6451. var matrix = new Matrix();
  6452. Matrix.ReflectionToRef(plane, matrix);
  6453. return matrix;
  6454. };
  6455. /**
  6456. * Computes a reflection matrix from a plane
  6457. * @param plane defines the reflection plane
  6458. * @param result defines the target matrix
  6459. */
  6460. Matrix.ReflectionToRef = function (plane, result) {
  6461. plane.normalize();
  6462. var x = plane.normal.x;
  6463. var y = plane.normal.y;
  6464. var z = plane.normal.z;
  6465. var temp = -2 * x;
  6466. var temp2 = -2 * y;
  6467. var temp3 = -2 * z;
  6468. result.m[0] = (temp * x) + 1;
  6469. result.m[1] = temp2 * x;
  6470. result.m[2] = temp3 * x;
  6471. result.m[3] = 0.0;
  6472. result.m[4] = temp * y;
  6473. result.m[5] = (temp2 * y) + 1;
  6474. result.m[6] = temp3 * y;
  6475. result.m[7] = 0.0;
  6476. result.m[8] = temp * z;
  6477. result.m[9] = temp2 * z;
  6478. result.m[10] = (temp3 * z) + 1;
  6479. result.m[11] = 0.0;
  6480. result.m[12] = temp * plane.d;
  6481. result.m[13] = temp2 * plane.d;
  6482. result.m[14] = temp3 * plane.d;
  6483. result.m[15] = 1.0;
  6484. result._markAsUpdated();
  6485. };
  6486. /**
  6487. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6488. * @param xaxis defines the value of the 1st axis
  6489. * @param yaxis defines the value of the 2nd axis
  6490. * @param zaxis defines the value of the 3rd axis
  6491. * @param result defines the target matrix
  6492. */
  6493. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6494. result.m[0] = xaxis.x;
  6495. result.m[1] = xaxis.y;
  6496. result.m[2] = xaxis.z;
  6497. result.m[3] = 0.0;
  6498. result.m[4] = yaxis.x;
  6499. result.m[5] = yaxis.y;
  6500. result.m[6] = yaxis.z;
  6501. result.m[7] = 0.0;
  6502. result.m[8] = zaxis.x;
  6503. result.m[9] = zaxis.y;
  6504. result.m[10] = zaxis.z;
  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. /**
  6513. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6514. * @param quat defines the quaternion to use
  6515. * @param result defines the target matrix
  6516. */
  6517. Matrix.FromQuaternionToRef = function (quat, result) {
  6518. var xx = quat.x * quat.x;
  6519. var yy = quat.y * quat.y;
  6520. var zz = quat.z * quat.z;
  6521. var xy = quat.x * quat.y;
  6522. var zw = quat.z * quat.w;
  6523. var zx = quat.z * quat.x;
  6524. var yw = quat.y * quat.w;
  6525. var yz = quat.y * quat.z;
  6526. var xw = quat.x * quat.w;
  6527. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6528. result.m[1] = 2.0 * (xy + zw);
  6529. result.m[2] = 2.0 * (zx - yw);
  6530. result.m[3] = 0.0;
  6531. result.m[4] = 2.0 * (xy - zw);
  6532. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6533. result.m[6] = 2.0 * (yz + xw);
  6534. result.m[7] = 0.0;
  6535. result.m[8] = 2.0 * (zx + yw);
  6536. result.m[9] = 2.0 * (yz - xw);
  6537. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6538. result.m[11] = 0.0;
  6539. result.m[12] = 0.0;
  6540. result.m[13] = 0.0;
  6541. result.m[14] = 0.0;
  6542. result.m[15] = 1.0;
  6543. result._markAsUpdated();
  6544. };
  6545. Matrix._tempQuaternion = new Quaternion();
  6546. Matrix._xAxis = Vector3.Zero();
  6547. Matrix._yAxis = Vector3.Zero();
  6548. Matrix._zAxis = Vector3.Zero();
  6549. Matrix._updateFlagSeed = 0;
  6550. Matrix._identityReadOnly = Matrix.Identity();
  6551. return Matrix;
  6552. }());
  6553. BABYLON.Matrix = Matrix;
  6554. var Plane = /** @class */ (function () {
  6555. /**
  6556. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6557. */
  6558. function Plane(a, b, c, d) {
  6559. this.normal = new Vector3(a, b, c);
  6560. this.d = d;
  6561. }
  6562. /**
  6563. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6564. */
  6565. Plane.prototype.asArray = function () {
  6566. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6567. };
  6568. // Methods
  6569. /**
  6570. * Returns a new plane copied from the current Plane.
  6571. */
  6572. Plane.prototype.clone = function () {
  6573. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6574. };
  6575. /**
  6576. * Returns the string "Plane".
  6577. */
  6578. Plane.prototype.getClassName = function () {
  6579. return "Plane";
  6580. };
  6581. /**
  6582. * Returns the Plane hash code.
  6583. */
  6584. Plane.prototype.getHashCode = function () {
  6585. var hash = this.normal.getHashCode();
  6586. hash = (hash * 397) ^ (this.d || 0);
  6587. return hash;
  6588. };
  6589. /**
  6590. * Normalize the current Plane in place.
  6591. * Returns the updated Plane.
  6592. */
  6593. Plane.prototype.normalize = function () {
  6594. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6595. var magnitude = 0.0;
  6596. if (norm !== 0) {
  6597. magnitude = 1.0 / norm;
  6598. }
  6599. this.normal.x *= magnitude;
  6600. this.normal.y *= magnitude;
  6601. this.normal.z *= magnitude;
  6602. this.d *= magnitude;
  6603. return this;
  6604. };
  6605. /**
  6606. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6607. */
  6608. Plane.prototype.transform = function (transformation) {
  6609. var transposedMatrix = Matrix.Transpose(transformation);
  6610. var x = this.normal.x;
  6611. var y = this.normal.y;
  6612. var z = this.normal.z;
  6613. var d = this.d;
  6614. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6615. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6616. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6617. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6618. return new Plane(normalX, normalY, normalZ, finalD);
  6619. };
  6620. /**
  6621. * Returns the dot product (float) of the point coordinates and the plane normal.
  6622. */
  6623. Plane.prototype.dotCoordinate = function (point) {
  6624. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6625. };
  6626. /**
  6627. * Updates the current Plane from the plane defined by the three given points.
  6628. * Returns the updated Plane.
  6629. */
  6630. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6631. var x1 = point2.x - point1.x;
  6632. var y1 = point2.y - point1.y;
  6633. var z1 = point2.z - point1.z;
  6634. var x2 = point3.x - point1.x;
  6635. var y2 = point3.y - point1.y;
  6636. var z2 = point3.z - point1.z;
  6637. var yz = (y1 * z2) - (z1 * y2);
  6638. var xz = (z1 * x2) - (x1 * z2);
  6639. var xy = (x1 * y2) - (y1 * x2);
  6640. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6641. var invPyth;
  6642. if (pyth !== 0) {
  6643. invPyth = 1.0 / pyth;
  6644. }
  6645. else {
  6646. invPyth = 0.0;
  6647. }
  6648. this.normal.x = yz * invPyth;
  6649. this.normal.y = xz * invPyth;
  6650. this.normal.z = xy * invPyth;
  6651. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6652. return this;
  6653. };
  6654. /**
  6655. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6656. */
  6657. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6658. var dot = Vector3.Dot(this.normal, direction);
  6659. return (dot <= epsilon);
  6660. };
  6661. /**
  6662. * Returns the signed distance (float) from the given point to the Plane.
  6663. */
  6664. Plane.prototype.signedDistanceTo = function (point) {
  6665. return Vector3.Dot(point, this.normal) + this.d;
  6666. };
  6667. // Statics
  6668. /**
  6669. * Returns a new Plane from the given array.
  6670. */
  6671. Plane.FromArray = function (array) {
  6672. return new Plane(array[0], array[1], array[2], array[3]);
  6673. };
  6674. /**
  6675. * Returns a new Plane defined by the three given points.
  6676. */
  6677. Plane.FromPoints = function (point1, point2, point3) {
  6678. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6679. result.copyFromPoints(point1, point2, point3);
  6680. return result;
  6681. };
  6682. /**
  6683. * Returns a new Plane the normal vector to this plane at the given origin point.
  6684. * Note : the vector "normal" is updated because normalized.
  6685. */
  6686. Plane.FromPositionAndNormal = function (origin, normal) {
  6687. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6688. normal.normalize();
  6689. result.normal = normal;
  6690. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6691. return result;
  6692. };
  6693. /**
  6694. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6695. */
  6696. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6697. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6698. return Vector3.Dot(point, normal) + d;
  6699. };
  6700. return Plane;
  6701. }());
  6702. BABYLON.Plane = Plane;
  6703. var Viewport = /** @class */ (function () {
  6704. /**
  6705. * Creates a Viewport object located at (x, y) and sized (width, height).
  6706. */
  6707. function Viewport(x, y, width, height) {
  6708. this.x = x;
  6709. this.y = y;
  6710. this.width = width;
  6711. this.height = height;
  6712. }
  6713. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6714. if (renderWidthOrEngine.getRenderWidth) {
  6715. var engine = renderWidthOrEngine;
  6716. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6717. }
  6718. var renderWidth = renderWidthOrEngine;
  6719. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6720. };
  6721. /**
  6722. * Returns a new Viewport copied from the current one.
  6723. */
  6724. Viewport.prototype.clone = function () {
  6725. return new Viewport(this.x, this.y, this.width, this.height);
  6726. };
  6727. return Viewport;
  6728. }());
  6729. BABYLON.Viewport = Viewport;
  6730. var Frustum = /** @class */ (function () {
  6731. function Frustum() {
  6732. }
  6733. /**
  6734. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6735. */
  6736. Frustum.GetPlanes = function (transform) {
  6737. var frustumPlanes = [];
  6738. for (var index = 0; index < 6; index++) {
  6739. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6740. }
  6741. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6742. return frustumPlanes;
  6743. };
  6744. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6745. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6746. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6747. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6748. frustumPlane.d = transform.m[15] + transform.m[14];
  6749. frustumPlane.normalize();
  6750. };
  6751. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6752. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6753. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6754. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6755. frustumPlane.d = transform.m[15] - transform.m[14];
  6756. frustumPlane.normalize();
  6757. };
  6758. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6759. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6760. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6761. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6762. frustumPlane.d = transform.m[15] + transform.m[12];
  6763. frustumPlane.normalize();
  6764. };
  6765. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6766. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6767. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6768. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6769. frustumPlane.d = transform.m[15] - transform.m[12];
  6770. frustumPlane.normalize();
  6771. };
  6772. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6773. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6774. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6775. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6776. frustumPlane.d = transform.m[15] - transform.m[13];
  6777. frustumPlane.normalize();
  6778. };
  6779. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6780. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6781. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6782. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6783. frustumPlane.d = transform.m[15] + transform.m[13];
  6784. frustumPlane.normalize();
  6785. };
  6786. /**
  6787. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6788. */
  6789. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6790. // Near
  6791. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6792. // Far
  6793. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6794. // Left
  6795. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6796. // Right
  6797. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6798. // Top
  6799. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6800. // Bottom
  6801. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6802. };
  6803. return Frustum;
  6804. }());
  6805. BABYLON.Frustum = Frustum;
  6806. /** Defines supported spaces */
  6807. var Space;
  6808. (function (Space) {
  6809. /** Local (object) space */
  6810. Space[Space["LOCAL"] = 0] = "LOCAL";
  6811. /** World space */
  6812. Space[Space["WORLD"] = 1] = "WORLD";
  6813. /** Bone space */
  6814. Space[Space["BONE"] = 2] = "BONE";
  6815. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6816. /** Defines the 3 main axes */
  6817. var Axis = /** @class */ (function () {
  6818. function Axis() {
  6819. }
  6820. /** X axis */
  6821. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6822. /** Y axis */
  6823. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6824. /** Z axis */
  6825. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6826. return Axis;
  6827. }());
  6828. BABYLON.Axis = Axis;
  6829. ;
  6830. var BezierCurve = /** @class */ (function () {
  6831. function BezierCurve() {
  6832. }
  6833. /**
  6834. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6835. */
  6836. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6837. // Extract X (which is equal to time here)
  6838. var f0 = 1 - 3 * x2 + 3 * x1;
  6839. var f1 = 3 * x2 - 6 * x1;
  6840. var f2 = 3 * x1;
  6841. var refinedT = t;
  6842. for (var i = 0; i < 5; i++) {
  6843. var refinedT2 = refinedT * refinedT;
  6844. var refinedT3 = refinedT2 * refinedT;
  6845. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6846. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6847. refinedT -= (x - t) * slope;
  6848. refinedT = Math.min(1, Math.max(0, refinedT));
  6849. }
  6850. // Resolve cubic bezier for the given x
  6851. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6852. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6853. Math.pow(refinedT, 3);
  6854. };
  6855. return BezierCurve;
  6856. }());
  6857. BABYLON.BezierCurve = BezierCurve;
  6858. /**
  6859. * Defines potential orientation for back face culling
  6860. */
  6861. var Orientation;
  6862. (function (Orientation) {
  6863. /**
  6864. * Clockwise
  6865. */
  6866. Orientation[Orientation["CW"] = 0] = "CW";
  6867. /** Counter clockwise */
  6868. Orientation[Orientation["CCW"] = 1] = "CCW";
  6869. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6870. /**
  6871. * Defines angle representation
  6872. */
  6873. var Angle = /** @class */ (function () {
  6874. /**
  6875. * Creates an Angle object of "radians" radians (float).
  6876. */
  6877. function Angle(radians) {
  6878. this._radians = radians;
  6879. if (this._radians < 0.0)
  6880. this._radians += (2.0 * Math.PI);
  6881. }
  6882. /**
  6883. * Get value in degrees
  6884. * @returns the Angle value in degrees (float)
  6885. */
  6886. Angle.prototype.degrees = function () {
  6887. return this._radians * 180.0 / Math.PI;
  6888. };
  6889. /**
  6890. * Get value in radians
  6891. * @returns the Angle value in radians (float)
  6892. */
  6893. Angle.prototype.radians = function () {
  6894. return this._radians;
  6895. };
  6896. /**
  6897. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6898. * @param a defines first vector
  6899. * @param b defines second vector
  6900. * @returns a new Angle
  6901. */
  6902. Angle.BetweenTwoPoints = function (a, b) {
  6903. var delta = b.subtract(a);
  6904. var theta = Math.atan2(delta.y, delta.x);
  6905. return new Angle(theta);
  6906. };
  6907. /**
  6908. * Gets a new Angle object from the given float in radians
  6909. * @param radians defines the angle value in radians
  6910. * @returns a new Angle
  6911. */
  6912. Angle.FromRadians = function (radians) {
  6913. return new Angle(radians);
  6914. };
  6915. /**
  6916. * Gets a new Angle object from the given float in degrees
  6917. * @param degrees defines the angle value in degrees
  6918. * @returns a new Angle
  6919. */
  6920. Angle.FromDegrees = function (degrees) {
  6921. return new Angle(degrees * Math.PI / 180.0);
  6922. };
  6923. return Angle;
  6924. }());
  6925. BABYLON.Angle = Angle;
  6926. var Arc2 = /** @class */ (function () {
  6927. /**
  6928. * Creates an Arc object from the three given points : start, middle and end.
  6929. */
  6930. function Arc2(startPoint, midPoint, endPoint) {
  6931. this.startPoint = startPoint;
  6932. this.midPoint = midPoint;
  6933. this.endPoint = endPoint;
  6934. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6935. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6936. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6937. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6938. 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);
  6939. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6940. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6941. var a1 = this.startAngle.degrees();
  6942. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6943. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6944. // angles correction
  6945. if (a2 - a1 > +180.0)
  6946. a2 -= 360.0;
  6947. if (a2 - a1 < -180.0)
  6948. a2 += 360.0;
  6949. if (a3 - a2 > +180.0)
  6950. a3 -= 360.0;
  6951. if (a3 - a2 < -180.0)
  6952. a3 += 360.0;
  6953. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6954. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6955. }
  6956. return Arc2;
  6957. }());
  6958. BABYLON.Arc2 = Arc2;
  6959. var Path2 = /** @class */ (function () {
  6960. /**
  6961. * Creates a Path2 object from the starting 2D coordinates x and y.
  6962. */
  6963. function Path2(x, y) {
  6964. this._points = new Array();
  6965. this._length = 0.0;
  6966. this.closed = false;
  6967. this._points.push(new Vector2(x, y));
  6968. }
  6969. /**
  6970. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6971. * Returns the updated Path2.
  6972. */
  6973. Path2.prototype.addLineTo = function (x, y) {
  6974. if (this.closed) {
  6975. return this;
  6976. }
  6977. var newPoint = new Vector2(x, y);
  6978. var previousPoint = this._points[this._points.length - 1];
  6979. this._points.push(newPoint);
  6980. this._length += newPoint.subtract(previousPoint).length();
  6981. return this;
  6982. };
  6983. /**
  6984. * 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.
  6985. * Returns the updated Path2.
  6986. */
  6987. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6988. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6989. if (this.closed) {
  6990. return this;
  6991. }
  6992. var startPoint = this._points[this._points.length - 1];
  6993. var midPoint = new Vector2(midX, midY);
  6994. var endPoint = new Vector2(endX, endY);
  6995. var arc = new Arc2(startPoint, midPoint, endPoint);
  6996. var increment = arc.angle.radians() / numberOfSegments;
  6997. if (arc.orientation === Orientation.CW)
  6998. increment *= -1;
  6999. var currentAngle = arc.startAngle.radians() + increment;
  7000. for (var i = 0; i < numberOfSegments; i++) {
  7001. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7002. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7003. this.addLineTo(x, y);
  7004. currentAngle += increment;
  7005. }
  7006. return this;
  7007. };
  7008. /**
  7009. * Closes the Path2.
  7010. * Returns the Path2.
  7011. */
  7012. Path2.prototype.close = function () {
  7013. this.closed = true;
  7014. return this;
  7015. };
  7016. /**
  7017. * Returns the Path2 total length (float).
  7018. */
  7019. Path2.prototype.length = function () {
  7020. var result = this._length;
  7021. if (!this.closed) {
  7022. var lastPoint = this._points[this._points.length - 1];
  7023. var firstPoint = this._points[0];
  7024. result += (firstPoint.subtract(lastPoint).length());
  7025. }
  7026. return result;
  7027. };
  7028. /**
  7029. * Returns the Path2 internal array of points.
  7030. */
  7031. Path2.prototype.getPoints = function () {
  7032. return this._points;
  7033. };
  7034. /**
  7035. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7036. */
  7037. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7038. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7039. return Vector2.Zero();
  7040. }
  7041. var lengthPosition = normalizedLengthPosition * this.length();
  7042. var previousOffset = 0;
  7043. for (var i = 0; i < this._points.length; i++) {
  7044. var j = (i + 1) % this._points.length;
  7045. var a = this._points[i];
  7046. var b = this._points[j];
  7047. var bToA = b.subtract(a);
  7048. var nextOffset = (bToA.length() + previousOffset);
  7049. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7050. var dir = bToA.normalize();
  7051. var localOffset = lengthPosition - previousOffset;
  7052. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7053. }
  7054. previousOffset = nextOffset;
  7055. }
  7056. return Vector2.Zero();
  7057. };
  7058. /**
  7059. * Returns a new Path2 starting at the coordinates (x, y).
  7060. */
  7061. Path2.StartingAt = function (x, y) {
  7062. return new Path2(x, y);
  7063. };
  7064. return Path2;
  7065. }());
  7066. BABYLON.Path2 = Path2;
  7067. var Path3D = /** @class */ (function () {
  7068. /**
  7069. * new Path3D(path, normal, raw)
  7070. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7071. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7072. * path : an array of Vector3, the curve axis of the Path3D
  7073. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7074. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7075. */
  7076. function Path3D(path, firstNormal, raw) {
  7077. if (firstNormal === void 0) { firstNormal = null; }
  7078. this.path = path;
  7079. this._curve = new Array();
  7080. this._distances = new Array();
  7081. this._tangents = new Array();
  7082. this._normals = new Array();
  7083. this._binormals = new Array();
  7084. for (var p = 0; p < path.length; p++) {
  7085. this._curve[p] = path[p].clone(); // hard copy
  7086. }
  7087. this._raw = raw || false;
  7088. this._compute(firstNormal);
  7089. }
  7090. /**
  7091. * Returns the Path3D array of successive Vector3 designing its curve.
  7092. */
  7093. Path3D.prototype.getCurve = function () {
  7094. return this._curve;
  7095. };
  7096. /**
  7097. * Returns an array populated with tangent vectors on each Path3D curve point.
  7098. */
  7099. Path3D.prototype.getTangents = function () {
  7100. return this._tangents;
  7101. };
  7102. /**
  7103. * Returns an array populated with normal vectors on each Path3D curve point.
  7104. */
  7105. Path3D.prototype.getNormals = function () {
  7106. return this._normals;
  7107. };
  7108. /**
  7109. * Returns an array populated with binormal vectors on each Path3D curve point.
  7110. */
  7111. Path3D.prototype.getBinormals = function () {
  7112. return this._binormals;
  7113. };
  7114. /**
  7115. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7116. */
  7117. Path3D.prototype.getDistances = function () {
  7118. return this._distances;
  7119. };
  7120. /**
  7121. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7122. * Returns the same object updated.
  7123. */
  7124. Path3D.prototype.update = function (path, firstNormal) {
  7125. if (firstNormal === void 0) { firstNormal = null; }
  7126. for (var p = 0; p < path.length; p++) {
  7127. this._curve[p].x = path[p].x;
  7128. this._curve[p].y = path[p].y;
  7129. this._curve[p].z = path[p].z;
  7130. }
  7131. this._compute(firstNormal);
  7132. return this;
  7133. };
  7134. // private function compute() : computes tangents, normals and binormals
  7135. Path3D.prototype._compute = function (firstNormal) {
  7136. var l = this._curve.length;
  7137. // first and last tangents
  7138. this._tangents[0] = this._getFirstNonNullVector(0);
  7139. if (!this._raw) {
  7140. this._tangents[0].normalize();
  7141. }
  7142. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7143. if (!this._raw) {
  7144. this._tangents[l - 1].normalize();
  7145. }
  7146. // normals and binormals at first point : arbitrary vector with _normalVector()
  7147. var tg0 = this._tangents[0];
  7148. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7149. this._normals[0] = pp0;
  7150. if (!this._raw) {
  7151. this._normals[0].normalize();
  7152. }
  7153. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7154. if (!this._raw) {
  7155. this._binormals[0].normalize();
  7156. }
  7157. this._distances[0] = 0.0;
  7158. // normals and binormals : next points
  7159. var prev; // previous vector (segment)
  7160. var cur; // current vector (segment)
  7161. var curTang; // current tangent
  7162. // previous normal
  7163. var prevBinor; // previous binormal
  7164. for (var i = 1; i < l; i++) {
  7165. // tangents
  7166. prev = this._getLastNonNullVector(i);
  7167. if (i < l - 1) {
  7168. cur = this._getFirstNonNullVector(i);
  7169. this._tangents[i] = prev.add(cur);
  7170. this._tangents[i].normalize();
  7171. }
  7172. this._distances[i] = this._distances[i - 1] + prev.length();
  7173. // normals and binormals
  7174. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7175. curTang = this._tangents[i];
  7176. prevBinor = this._binormals[i - 1];
  7177. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7178. if (!this._raw) {
  7179. this._normals[i].normalize();
  7180. }
  7181. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7182. if (!this._raw) {
  7183. this._binormals[i].normalize();
  7184. }
  7185. }
  7186. };
  7187. // private function getFirstNonNullVector(index)
  7188. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7189. Path3D.prototype._getFirstNonNullVector = function (index) {
  7190. var i = 1;
  7191. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7192. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7193. i++;
  7194. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7195. }
  7196. return nNVector;
  7197. };
  7198. // private function getLastNonNullVector(index)
  7199. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7200. Path3D.prototype._getLastNonNullVector = function (index) {
  7201. var i = 1;
  7202. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7203. while (nLVector.length() === 0 && index > i + 1) {
  7204. i++;
  7205. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7206. }
  7207. return nLVector;
  7208. };
  7209. // private function normalVector(v0, vt, va) :
  7210. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7211. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7212. Path3D.prototype._normalVector = function (v0, vt, va) {
  7213. var normal0;
  7214. var tgl = vt.length();
  7215. if (tgl === 0.0) {
  7216. tgl = 1.0;
  7217. }
  7218. if (va === undefined || va === null) {
  7219. var point;
  7220. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7221. point = new Vector3(0.0, -1.0, 0.0);
  7222. }
  7223. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7224. point = new Vector3(1.0, 0.0, 0.0);
  7225. }
  7226. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7227. point = new Vector3(0.0, 0.0, 1.0);
  7228. }
  7229. else {
  7230. point = Vector3.Zero();
  7231. }
  7232. normal0 = Vector3.Cross(vt, point);
  7233. }
  7234. else {
  7235. normal0 = Vector3.Cross(vt, va);
  7236. Vector3.CrossToRef(normal0, vt, normal0);
  7237. }
  7238. normal0.normalize();
  7239. return normal0;
  7240. };
  7241. return Path3D;
  7242. }());
  7243. BABYLON.Path3D = Path3D;
  7244. var Curve3 = /** @class */ (function () {
  7245. /**
  7246. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7247. * A Curve3 is designed from a series of successive Vector3.
  7248. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7249. */
  7250. function Curve3(points) {
  7251. this._length = 0.0;
  7252. this._points = points;
  7253. this._length = this._computeLength(points);
  7254. }
  7255. /**
  7256. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7257. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7258. * @param v1 (Vector3) the control point
  7259. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7260. * @param nbPoints (integer) the wanted number of points in the curve
  7261. */
  7262. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7263. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7264. var bez = new Array();
  7265. var equation = function (t, val0, val1, val2) {
  7266. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7267. return res;
  7268. };
  7269. for (var i = 0; i <= nbPoints; i++) {
  7270. 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)));
  7271. }
  7272. return new Curve3(bez);
  7273. };
  7274. /**
  7275. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7276. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7277. * @param v1 (Vector3) the first control point
  7278. * @param v2 (Vector3) the second control point
  7279. * @param v3 (Vector3) the end point of the Cubic Bezier
  7280. * @param nbPoints (integer) the wanted number of points in the curve
  7281. */
  7282. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7283. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7284. var bez = new Array();
  7285. var equation = function (t, val0, val1, val2, val3) {
  7286. 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;
  7287. return res;
  7288. };
  7289. for (var i = 0; i <= nbPoints; i++) {
  7290. 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)));
  7291. }
  7292. return new Curve3(bez);
  7293. };
  7294. /**
  7295. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7296. * @param p1 (Vector3) the origin point of the Hermite Spline
  7297. * @param t1 (Vector3) the tangent vector at the origin point
  7298. * @param p2 (Vector3) the end point of the Hermite Spline
  7299. * @param t2 (Vector3) the tangent vector at the end point
  7300. * @param nbPoints (integer) the wanted number of points in the curve
  7301. */
  7302. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7303. var hermite = new Array();
  7304. var step = 1.0 / nbPoints;
  7305. for (var i = 0; i <= nbPoints; i++) {
  7306. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7307. }
  7308. return new Curve3(hermite);
  7309. };
  7310. /**
  7311. * Returns a Curve3 object along a CatmullRom Spline curve :
  7312. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7313. * @param nbPoints (integer) the wanted number of points between each curve control points
  7314. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7315. */
  7316. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7317. var catmullRom = new Array();
  7318. var step = 1.0 / nbPoints;
  7319. var amount = 0.0;
  7320. if (closed) {
  7321. var pointsCount = points.length;
  7322. for (var i = 0; i < pointsCount; i++) {
  7323. amount = 0;
  7324. for (var c = 0; c < nbPoints; c++) {
  7325. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7326. amount += step;
  7327. }
  7328. }
  7329. catmullRom.push(catmullRom[0]);
  7330. }
  7331. else {
  7332. var totalPoints = new Array();
  7333. totalPoints.push(points[0].clone());
  7334. Array.prototype.push.apply(totalPoints, points);
  7335. totalPoints.push(points[points.length - 1].clone());
  7336. for (var i = 0; i < totalPoints.length - 3; i++) {
  7337. amount = 0;
  7338. for (var c = 0; c < nbPoints; c++) {
  7339. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7340. amount += step;
  7341. }
  7342. }
  7343. i--;
  7344. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7345. }
  7346. return new Curve3(catmullRom);
  7347. };
  7348. /**
  7349. * Returns the Curve3 stored array of successive Vector3
  7350. */
  7351. Curve3.prototype.getPoints = function () {
  7352. return this._points;
  7353. };
  7354. /**
  7355. * Returns the computed length (float) of the curve.
  7356. */
  7357. Curve3.prototype.length = function () {
  7358. return this._length;
  7359. };
  7360. /**
  7361. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7362. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7363. * curveA and curveB keep unchanged.
  7364. */
  7365. Curve3.prototype.continue = function (curve) {
  7366. var lastPoint = this._points[this._points.length - 1];
  7367. var continuedPoints = this._points.slice();
  7368. var curvePoints = curve.getPoints();
  7369. for (var i = 1; i < curvePoints.length; i++) {
  7370. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7371. }
  7372. var continuedCurve = new Curve3(continuedPoints);
  7373. return continuedCurve;
  7374. };
  7375. Curve3.prototype._computeLength = function (path) {
  7376. var l = 0;
  7377. for (var i = 1; i < path.length; i++) {
  7378. l += (path[i].subtract(path[i - 1])).length();
  7379. }
  7380. return l;
  7381. };
  7382. return Curve3;
  7383. }());
  7384. BABYLON.Curve3 = Curve3;
  7385. // Vertex formats
  7386. var PositionNormalVertex = /** @class */ (function () {
  7387. function PositionNormalVertex(position, normal) {
  7388. if (position === void 0) { position = Vector3.Zero(); }
  7389. if (normal === void 0) { normal = Vector3.Up(); }
  7390. this.position = position;
  7391. this.normal = normal;
  7392. }
  7393. PositionNormalVertex.prototype.clone = function () {
  7394. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7395. };
  7396. return PositionNormalVertex;
  7397. }());
  7398. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7399. var PositionNormalTextureVertex = /** @class */ (function () {
  7400. function PositionNormalTextureVertex(position, normal, uv) {
  7401. if (position === void 0) { position = Vector3.Zero(); }
  7402. if (normal === void 0) { normal = Vector3.Up(); }
  7403. if (uv === void 0) { uv = Vector2.Zero(); }
  7404. this.position = position;
  7405. this.normal = normal;
  7406. this.uv = uv;
  7407. }
  7408. PositionNormalTextureVertex.prototype.clone = function () {
  7409. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7410. };
  7411. return PositionNormalTextureVertex;
  7412. }());
  7413. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7414. // Temporary pre-allocated objects for engine internal use
  7415. // usage in any internal function :
  7416. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7417. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7418. var Tmp = /** @class */ (function () {
  7419. function Tmp() {
  7420. }
  7421. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7422. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7423. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7424. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7425. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7426. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7427. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7428. Matrix.Zero(), Matrix.Zero(),
  7429. Matrix.Zero(), Matrix.Zero(),
  7430. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7431. return Tmp;
  7432. }());
  7433. BABYLON.Tmp = Tmp;
  7434. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7435. var MathTmp = /** @class */ (function () {
  7436. function MathTmp() {
  7437. }
  7438. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7439. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7440. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7441. return MathTmp;
  7442. }());
  7443. })(BABYLON || (BABYLON = {}));
  7444. //# sourceMappingURL=babylon.math.js.map
  7445. var BABYLON;
  7446. (function (BABYLON) {
  7447. var Scalar = /** @class */ (function () {
  7448. function Scalar() {
  7449. }
  7450. /**
  7451. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7452. */
  7453. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7454. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7455. var num = a - b;
  7456. return -epsilon <= num && num <= epsilon;
  7457. };
  7458. /**
  7459. * Returns a string : the upper case translation of the number i to hexadecimal.
  7460. */
  7461. Scalar.ToHex = function (i) {
  7462. var str = i.toString(16);
  7463. if (i <= 15) {
  7464. return ("0" + str).toUpperCase();
  7465. }
  7466. return str.toUpperCase();
  7467. };
  7468. /**
  7469. * Returns -1 if value is negative and +1 is value is positive.
  7470. * Returns the value itself if it's equal to zero.
  7471. */
  7472. Scalar.Sign = function (value) {
  7473. value = +value; // convert to a number
  7474. if (value === 0 || isNaN(value))
  7475. return value;
  7476. return value > 0 ? 1 : -1;
  7477. };
  7478. /**
  7479. * Returns the value itself if it's between min and max.
  7480. * Returns min if the value is lower than min.
  7481. * Returns max if the value is greater than max.
  7482. */
  7483. Scalar.Clamp = function (value, min, max) {
  7484. if (min === void 0) { min = 0; }
  7485. if (max === void 0) { max = 1; }
  7486. return Math.min(max, Math.max(min, value));
  7487. };
  7488. /**
  7489. * Returns the log2 of value.
  7490. */
  7491. Scalar.Log2 = function (value) {
  7492. return Math.log(value) * Math.LOG2E;
  7493. };
  7494. /**
  7495. * Loops the value, so that it is never larger than length and never smaller than 0.
  7496. *
  7497. * This is similar to the modulo operator but it works with floating point numbers.
  7498. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7499. * With t = 5 and length = 2.5, the result would be 0.0.
  7500. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7501. */
  7502. Scalar.Repeat = function (value, length) {
  7503. return value - Math.floor(value / length) * length;
  7504. };
  7505. /**
  7506. * Normalize the value between 0.0 and 1.0 using min and max values
  7507. */
  7508. Scalar.Normalize = function (value, min, max) {
  7509. return (value - min) / (max - min);
  7510. };
  7511. /**
  7512. * Denormalize the value from 0.0 and 1.0 using min and max values
  7513. */
  7514. Scalar.Denormalize = function (normalized, min, max) {
  7515. return (normalized * (max - min) + min);
  7516. };
  7517. /**
  7518. * Calculates the shortest difference between two given angles given in degrees.
  7519. */
  7520. Scalar.DeltaAngle = function (current, target) {
  7521. var num = Scalar.Repeat(target - current, 360.0);
  7522. if (num > 180.0) {
  7523. num -= 360.0;
  7524. }
  7525. return num;
  7526. };
  7527. /**
  7528. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7529. *
  7530. * The returned value will move back and forth between 0 and length
  7531. */
  7532. Scalar.PingPong = function (tx, length) {
  7533. var t = Scalar.Repeat(tx, length * 2.0);
  7534. return length - Math.abs(t - length);
  7535. };
  7536. /**
  7537. * Interpolates between min and max with smoothing at the limits.
  7538. *
  7539. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7540. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7541. */
  7542. Scalar.SmoothStep = function (from, to, tx) {
  7543. var t = Scalar.Clamp(tx);
  7544. t = -2.0 * t * t * t + 3.0 * t * t;
  7545. return to * t + from * (1.0 - t);
  7546. };
  7547. /**
  7548. * Moves a value current towards target.
  7549. *
  7550. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7551. * Negative values of maxDelta pushes the value away from target.
  7552. */
  7553. Scalar.MoveTowards = function (current, target, maxDelta) {
  7554. var result = 0;
  7555. if (Math.abs(target - current) <= maxDelta) {
  7556. result = target;
  7557. }
  7558. else {
  7559. result = current + Scalar.Sign(target - current) * maxDelta;
  7560. }
  7561. return result;
  7562. };
  7563. /**
  7564. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7565. *
  7566. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7567. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7568. */
  7569. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7570. var num = Scalar.DeltaAngle(current, target);
  7571. var result = 0;
  7572. if (-maxDelta < num && num < maxDelta) {
  7573. result = target;
  7574. }
  7575. else {
  7576. target = current + num;
  7577. result = Scalar.MoveTowards(current, target, maxDelta);
  7578. }
  7579. return result;
  7580. };
  7581. /**
  7582. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7583. */
  7584. Scalar.Lerp = function (start, end, amount) {
  7585. return start + ((end - start) * amount);
  7586. };
  7587. /**
  7588. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7589. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7590. */
  7591. Scalar.LerpAngle = function (start, end, amount) {
  7592. var num = Scalar.Repeat(end - start, 360.0);
  7593. if (num > 180.0) {
  7594. num -= 360.0;
  7595. }
  7596. return start + num * Scalar.Clamp(amount);
  7597. };
  7598. /**
  7599. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7600. */
  7601. Scalar.InverseLerp = function (a, b, value) {
  7602. var result = 0;
  7603. if (a != b) {
  7604. result = Scalar.Clamp((value - a) / (b - a));
  7605. }
  7606. else {
  7607. result = 0.0;
  7608. }
  7609. return result;
  7610. };
  7611. /**
  7612. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7613. */
  7614. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7615. var squared = amount * amount;
  7616. var cubed = amount * squared;
  7617. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7618. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7619. var part3 = (cubed - (2.0 * squared)) + amount;
  7620. var part4 = cubed - squared;
  7621. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7622. };
  7623. /**
  7624. * Returns a random float number between and min and max values
  7625. */
  7626. Scalar.RandomRange = function (min, max) {
  7627. if (min === max)
  7628. return min;
  7629. return ((Math.random() * (max - min)) + min);
  7630. };
  7631. /**
  7632. * This function returns percentage of a number in a given range.
  7633. *
  7634. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7635. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7636. */
  7637. Scalar.RangeToPercent = function (number, min, max) {
  7638. return ((number - min) / (max - min));
  7639. };
  7640. /**
  7641. * This function returns number that corresponds to the percentage in a given range.
  7642. *
  7643. * PercentToRange(0.34,0,100) will return 34.
  7644. */
  7645. Scalar.PercentToRange = function (percent, min, max) {
  7646. return ((max - min) * percent + min);
  7647. };
  7648. /**
  7649. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7650. * @param angle The angle to normalize in radian.
  7651. * @return The converted angle.
  7652. */
  7653. Scalar.NormalizeRadians = function (angle) {
  7654. // More precise but slower version kept for reference.
  7655. // angle = angle % Tools.TwoPi;
  7656. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7657. //if (angle > Math.PI) {
  7658. // angle -= Tools.TwoPi;
  7659. //}
  7660. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7661. return angle;
  7662. };
  7663. /**
  7664. * Two pi constants convenient for computation.
  7665. */
  7666. Scalar.TwoPi = Math.PI * 2;
  7667. return Scalar;
  7668. }());
  7669. BABYLON.Scalar = Scalar;
  7670. })(BABYLON || (BABYLON = {}));
  7671. //# sourceMappingURL=babylon.math.scalar.js.map
  7672. //# sourceMappingURL=babylon.mixins.js.map
  7673. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7674. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7675. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7676. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7677. //# sourceMappingURL=babylon.webgl2.js.map
  7678. var BABYLON;
  7679. (function (BABYLON) {
  7680. var __decoratorInitialStore = {};
  7681. var __mergedStore = {};
  7682. var _copySource = function (creationFunction, source, instanciate) {
  7683. var destination = creationFunction();
  7684. // Tags
  7685. if (BABYLON.Tags) {
  7686. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7687. }
  7688. var classStore = getMergedStore(destination);
  7689. // Properties
  7690. for (var property in classStore) {
  7691. var propertyDescriptor = classStore[property];
  7692. var sourceProperty = source[property];
  7693. var propertyType = propertyDescriptor.type;
  7694. if (sourceProperty !== undefined && sourceProperty !== null) {
  7695. switch (propertyType) {
  7696. case 0: // Value
  7697. case 6: // Mesh reference
  7698. case 11: // Camera reference
  7699. destination[property] = sourceProperty;
  7700. break;
  7701. case 1: // Texture
  7702. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7703. break;
  7704. case 2: // Color3
  7705. case 3: // FresnelParameters
  7706. case 4: // Vector2
  7707. case 5: // Vector3
  7708. case 7: // Color Curves
  7709. case 10: // Quaternion
  7710. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7711. break;
  7712. }
  7713. }
  7714. }
  7715. return destination;
  7716. };
  7717. function getDirectStore(target) {
  7718. var classKey = target.getClassName();
  7719. if (!__decoratorInitialStore[classKey]) {
  7720. __decoratorInitialStore[classKey] = {};
  7721. }
  7722. return __decoratorInitialStore[classKey];
  7723. }
  7724. /**
  7725. * Return the list of properties flagged as serializable
  7726. * @param target: host object
  7727. */
  7728. function getMergedStore(target) {
  7729. var classKey = target.getClassName();
  7730. if (__mergedStore[classKey]) {
  7731. return __mergedStore[classKey];
  7732. }
  7733. __mergedStore[classKey] = {};
  7734. var store = __mergedStore[classKey];
  7735. var currentTarget = target;
  7736. var currentKey = classKey;
  7737. while (currentKey) {
  7738. var initialStore = __decoratorInitialStore[currentKey];
  7739. for (var property in initialStore) {
  7740. store[property] = initialStore[property];
  7741. }
  7742. var parent_1 = void 0;
  7743. var done = false;
  7744. do {
  7745. parent_1 = Object.getPrototypeOf(currentTarget);
  7746. if (!parent_1.getClassName) {
  7747. done = true;
  7748. break;
  7749. }
  7750. if (parent_1.getClassName() !== currentKey) {
  7751. break;
  7752. }
  7753. currentTarget = parent_1;
  7754. } while (parent_1);
  7755. if (done) {
  7756. break;
  7757. }
  7758. currentKey = parent_1.getClassName();
  7759. currentTarget = parent_1;
  7760. }
  7761. return store;
  7762. }
  7763. function generateSerializableMember(type, sourceName) {
  7764. return function (target, propertyKey) {
  7765. var classStore = getDirectStore(target);
  7766. if (!classStore[propertyKey]) {
  7767. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7768. }
  7769. };
  7770. }
  7771. function generateExpandMember(setCallback, targetKey) {
  7772. if (targetKey === void 0) { targetKey = null; }
  7773. return function (target, propertyKey) {
  7774. var key = targetKey || ("_" + propertyKey);
  7775. Object.defineProperty(target, propertyKey, {
  7776. get: function () {
  7777. return this[key];
  7778. },
  7779. set: function (value) {
  7780. if (this[key] === value) {
  7781. return;
  7782. }
  7783. this[key] = value;
  7784. target[setCallback].apply(this);
  7785. },
  7786. enumerable: true,
  7787. configurable: true
  7788. });
  7789. };
  7790. }
  7791. function expandToProperty(callback, targetKey) {
  7792. if (targetKey === void 0) { targetKey = null; }
  7793. return generateExpandMember(callback, targetKey);
  7794. }
  7795. BABYLON.expandToProperty = expandToProperty;
  7796. function serialize(sourceName) {
  7797. return generateSerializableMember(0, sourceName); // value member
  7798. }
  7799. BABYLON.serialize = serialize;
  7800. function serializeAsTexture(sourceName) {
  7801. return generateSerializableMember(1, sourceName); // texture member
  7802. }
  7803. BABYLON.serializeAsTexture = serializeAsTexture;
  7804. function serializeAsColor3(sourceName) {
  7805. return generateSerializableMember(2, sourceName); // color3 member
  7806. }
  7807. BABYLON.serializeAsColor3 = serializeAsColor3;
  7808. function serializeAsFresnelParameters(sourceName) {
  7809. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7810. }
  7811. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7812. function serializeAsVector2(sourceName) {
  7813. return generateSerializableMember(4, sourceName); // vector2 member
  7814. }
  7815. BABYLON.serializeAsVector2 = serializeAsVector2;
  7816. function serializeAsVector3(sourceName) {
  7817. return generateSerializableMember(5, sourceName); // vector3 member
  7818. }
  7819. BABYLON.serializeAsVector3 = serializeAsVector3;
  7820. function serializeAsMeshReference(sourceName) {
  7821. return generateSerializableMember(6, sourceName); // mesh reference member
  7822. }
  7823. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7824. function serializeAsColorCurves(sourceName) {
  7825. return generateSerializableMember(7, sourceName); // color curves
  7826. }
  7827. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7828. function serializeAsColor4(sourceName) {
  7829. return generateSerializableMember(8, sourceName); // color 4
  7830. }
  7831. BABYLON.serializeAsColor4 = serializeAsColor4;
  7832. function serializeAsImageProcessingConfiguration(sourceName) {
  7833. return generateSerializableMember(9, sourceName); // image processing
  7834. }
  7835. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7836. function serializeAsQuaternion(sourceName) {
  7837. return generateSerializableMember(10, sourceName); // quaternion member
  7838. }
  7839. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7840. /**
  7841. * Decorator used to define property that can be serialized as reference to a camera
  7842. * @param sourceName defines the name of the property to decorate
  7843. */
  7844. function serializeAsCameraReference(sourceName) {
  7845. return generateSerializableMember(11, sourceName); // camera reference member
  7846. }
  7847. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7848. var SerializationHelper = /** @class */ (function () {
  7849. function SerializationHelper() {
  7850. }
  7851. SerializationHelper.Serialize = function (entity, serializationObject) {
  7852. if (!serializationObject) {
  7853. serializationObject = {};
  7854. }
  7855. // Tags
  7856. if (BABYLON.Tags) {
  7857. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7858. }
  7859. var serializedProperties = getMergedStore(entity);
  7860. // Properties
  7861. for (var property in serializedProperties) {
  7862. var propertyDescriptor = serializedProperties[property];
  7863. var targetPropertyName = propertyDescriptor.sourceName || property;
  7864. var propertyType = propertyDescriptor.type;
  7865. var sourceProperty = entity[property];
  7866. if (sourceProperty !== undefined && sourceProperty !== null) {
  7867. switch (propertyType) {
  7868. case 0: // Value
  7869. serializationObject[targetPropertyName] = sourceProperty;
  7870. break;
  7871. case 1: // Texture
  7872. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7873. break;
  7874. case 2: // Color3
  7875. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7876. break;
  7877. case 3: // FresnelParameters
  7878. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7879. break;
  7880. case 4: // Vector2
  7881. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7882. break;
  7883. case 5: // Vector3
  7884. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7885. break;
  7886. case 6: // Mesh reference
  7887. serializationObject[targetPropertyName] = sourceProperty.id;
  7888. break;
  7889. case 7: // Color Curves
  7890. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7891. break;
  7892. case 8: // Color 4
  7893. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7894. break;
  7895. case 9: // Image Processing
  7896. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7897. break;
  7898. case 10: // Quaternion
  7899. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7900. break;
  7901. case 11: // Camera reference
  7902. serializationObject[targetPropertyName] = sourceProperty.id;
  7903. break;
  7904. }
  7905. }
  7906. }
  7907. return serializationObject;
  7908. };
  7909. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7910. if (rootUrl === void 0) { rootUrl = null; }
  7911. var destination = creationFunction();
  7912. if (!rootUrl) {
  7913. rootUrl = "";
  7914. }
  7915. // Tags
  7916. if (BABYLON.Tags) {
  7917. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7918. }
  7919. var classStore = getMergedStore(destination);
  7920. // Properties
  7921. for (var property in classStore) {
  7922. var propertyDescriptor = classStore[property];
  7923. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7924. var propertyType = propertyDescriptor.type;
  7925. if (sourceProperty !== undefined && sourceProperty !== null) {
  7926. var dest = destination;
  7927. switch (propertyType) {
  7928. case 0: // Value
  7929. dest[property] = sourceProperty;
  7930. break;
  7931. case 1: // Texture
  7932. if (scene) {
  7933. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7934. }
  7935. break;
  7936. case 2: // Color3
  7937. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7938. break;
  7939. case 3: // FresnelParameters
  7940. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7941. break;
  7942. case 4: // Vector2
  7943. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7944. break;
  7945. case 5: // Vector3
  7946. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7947. break;
  7948. case 6: // Mesh reference
  7949. if (scene) {
  7950. dest[property] = scene.getLastMeshByID(sourceProperty);
  7951. }
  7952. break;
  7953. case 7: // Color Curves
  7954. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7955. break;
  7956. case 8: // Color 4
  7957. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7958. break;
  7959. case 9: // Image Processing
  7960. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7961. break;
  7962. case 10: // Quaternion
  7963. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7964. break;
  7965. case 11: // Camera reference
  7966. if (scene) {
  7967. dest[property] = scene.getCameraByID(sourceProperty);
  7968. }
  7969. break;
  7970. }
  7971. }
  7972. }
  7973. return destination;
  7974. };
  7975. SerializationHelper.Clone = function (creationFunction, source) {
  7976. return _copySource(creationFunction, source, false);
  7977. };
  7978. SerializationHelper.Instanciate = function (creationFunction, source) {
  7979. return _copySource(creationFunction, source, true);
  7980. };
  7981. return SerializationHelper;
  7982. }());
  7983. BABYLON.SerializationHelper = SerializationHelper;
  7984. })(BABYLON || (BABYLON = {}));
  7985. //# sourceMappingURL=babylon.decorators.js.map
  7986. var BABYLON;
  7987. (function (BABYLON) {
  7988. /**
  7989. * Wrapper class for promise with external resolve and reject.
  7990. */
  7991. var Deferred = /** @class */ (function () {
  7992. /**
  7993. * Constructor for this deferred object.
  7994. */
  7995. function Deferred() {
  7996. var _this = this;
  7997. this.promise = new Promise(function (resolve, reject) {
  7998. _this._resolve = resolve;
  7999. _this._reject = reject;
  8000. });
  8001. }
  8002. Object.defineProperty(Deferred.prototype, "resolve", {
  8003. /**
  8004. * The resolve method of the promise associated with this deferred object.
  8005. */
  8006. get: function () {
  8007. return this._resolve;
  8008. },
  8009. enumerable: true,
  8010. configurable: true
  8011. });
  8012. Object.defineProperty(Deferred.prototype, "reject", {
  8013. /**
  8014. * The reject method of the promise associated with this deferred object.
  8015. */
  8016. get: function () {
  8017. return this._reject;
  8018. },
  8019. enumerable: true,
  8020. configurable: true
  8021. });
  8022. return Deferred;
  8023. }());
  8024. BABYLON.Deferred = Deferred;
  8025. })(BABYLON || (BABYLON = {}));
  8026. //# sourceMappingURL=babylon.deferred.js.map
  8027. var BABYLON;
  8028. (function (BABYLON) {
  8029. /**
  8030. * A class serves as a medium between the observable and its observers
  8031. */
  8032. var EventState = /** @class */ (function () {
  8033. /**
  8034. * Create a new EventState
  8035. * @param mask defines the mask associated with this state
  8036. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8037. * @param target defines the original target of the state
  8038. * @param currentTarget defines the current target of the state
  8039. */
  8040. function EventState(mask, skipNextObservers, target, currentTarget) {
  8041. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8042. this.initalize(mask, skipNextObservers, target, currentTarget);
  8043. }
  8044. /**
  8045. * Initialize the current event state
  8046. * @param mask defines the mask associated with this state
  8047. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8048. * @param target defines the original target of the state
  8049. * @param currentTarget defines the current target of the state
  8050. * @returns the current event state
  8051. */
  8052. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8053. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8054. this.mask = mask;
  8055. this.skipNextObservers = skipNextObservers;
  8056. this.target = target;
  8057. this.currentTarget = currentTarget;
  8058. return this;
  8059. };
  8060. return EventState;
  8061. }());
  8062. BABYLON.EventState = EventState;
  8063. /**
  8064. * Represent an Observer registered to a given Observable object.
  8065. */
  8066. var Observer = /** @class */ (function () {
  8067. /**
  8068. * Creates a new observer
  8069. * @param callback defines the callback to call when the observer is notified
  8070. * @param mask defines the mask of the observer (used to filter notifications)
  8071. * @param scope defines the current scope used to restore the JS context
  8072. */
  8073. function Observer(
  8074. /**
  8075. * Defines the callback to call when the observer is notified
  8076. */
  8077. callback,
  8078. /**
  8079. * Defines the mask of the observer (used to filter notifications)
  8080. */
  8081. mask,
  8082. /**
  8083. * Defines the current scope used to restore the JS context
  8084. */
  8085. scope) {
  8086. if (scope === void 0) { scope = null; }
  8087. this.callback = callback;
  8088. this.mask = mask;
  8089. this.scope = scope;
  8090. /** @hidden */
  8091. this._willBeUnregistered = false;
  8092. /**
  8093. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8094. */
  8095. this.unregisterOnNextCall = false;
  8096. }
  8097. return Observer;
  8098. }());
  8099. BABYLON.Observer = Observer;
  8100. /**
  8101. * Represent a list of observers registered to multiple Observables object.
  8102. */
  8103. var MultiObserver = /** @class */ (function () {
  8104. function MultiObserver() {
  8105. }
  8106. /**
  8107. * Release associated resources
  8108. */
  8109. MultiObserver.prototype.dispose = function () {
  8110. if (this._observers && this._observables) {
  8111. for (var index = 0; index < this._observers.length; index++) {
  8112. this._observables[index].remove(this._observers[index]);
  8113. }
  8114. }
  8115. this._observers = null;
  8116. this._observables = null;
  8117. };
  8118. /**
  8119. * Raise a callback when one of the observable will notify
  8120. * @param observables defines a list of observables to watch
  8121. * @param callback defines the callback to call on notification
  8122. * @param mask defines the mask used to filter notifications
  8123. * @param scope defines the current scope used to restore the JS context
  8124. * @returns the new MultiObserver
  8125. */
  8126. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8127. if (mask === void 0) { mask = -1; }
  8128. if (scope === void 0) { scope = null; }
  8129. var result = new MultiObserver();
  8130. result._observers = new Array();
  8131. result._observables = observables;
  8132. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8133. var observable = observables_1[_i];
  8134. var observer = observable.add(callback, mask, false, scope);
  8135. if (observer) {
  8136. result._observers.push(observer);
  8137. }
  8138. }
  8139. return result;
  8140. };
  8141. return MultiObserver;
  8142. }());
  8143. BABYLON.MultiObserver = MultiObserver;
  8144. /**
  8145. * The Observable class is a simple implementation of the Observable pattern.
  8146. *
  8147. * 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.
  8148. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8149. * 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).
  8150. * 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.
  8151. */
  8152. var Observable = /** @class */ (function () {
  8153. /**
  8154. * Creates a new observable
  8155. * @param onObserverAdded defines a callback to call when a new observer is added
  8156. */
  8157. function Observable(onObserverAdded) {
  8158. this._observers = new Array();
  8159. this._eventState = new EventState(0);
  8160. if (onObserverAdded) {
  8161. this._onObserverAdded = onObserverAdded;
  8162. }
  8163. }
  8164. /**
  8165. * Create a new Observer with the specified callback
  8166. * @param callback the callback that will be executed for that Observer
  8167. * @param mask the mask used to filter observers
  8168. * @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.
  8169. * @param scope optional scope for the callback to be called from
  8170. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8171. * @returns the new observer created for the callback
  8172. */
  8173. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8174. if (mask === void 0) { mask = -1; }
  8175. if (insertFirst === void 0) { insertFirst = false; }
  8176. if (scope === void 0) { scope = null; }
  8177. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8178. if (!callback) {
  8179. return null;
  8180. }
  8181. var observer = new Observer(callback, mask, scope);
  8182. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8183. if (insertFirst) {
  8184. this._observers.unshift(observer);
  8185. }
  8186. else {
  8187. this._observers.push(observer);
  8188. }
  8189. if (this._onObserverAdded) {
  8190. this._onObserverAdded(observer);
  8191. }
  8192. return observer;
  8193. };
  8194. /**
  8195. * Create a new Observer with the specified callback and unregisters after the next notification
  8196. * @param callback the callback that will be executed for that Observer
  8197. * @returns the new observer created for the callback
  8198. */
  8199. Observable.prototype.addOnce = function (callback) {
  8200. return this.add(callback, undefined, undefined, undefined, true);
  8201. };
  8202. /**
  8203. * Remove an Observer from the Observable object
  8204. * @param observer the instance of the Observer to remove
  8205. * @returns false if it doesn't belong to this Observable
  8206. */
  8207. Observable.prototype.remove = function (observer) {
  8208. if (!observer) {
  8209. return false;
  8210. }
  8211. var index = this._observers.indexOf(observer);
  8212. if (index !== -1) {
  8213. this._observers.splice(index, 1);
  8214. return true;
  8215. }
  8216. return false;
  8217. };
  8218. /**
  8219. * Remove a callback from the Observable object
  8220. * @param callback the callback to remove
  8221. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8222. * @returns false if it doesn't belong to this Observable
  8223. */
  8224. Observable.prototype.removeCallback = function (callback, scope) {
  8225. for (var index = 0; index < this._observers.length; index++) {
  8226. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8227. this._observers.splice(index, 1);
  8228. return true;
  8229. }
  8230. }
  8231. return false;
  8232. };
  8233. Observable.prototype._deferUnregister = function (observer) {
  8234. var _this = this;
  8235. observer.unregisterOnNextCall = false;
  8236. observer._willBeUnregistered = true;
  8237. BABYLON.Tools.SetImmediate(function () {
  8238. _this.remove(observer);
  8239. });
  8240. };
  8241. /**
  8242. * Notify all Observers by calling their respective callback with the given data
  8243. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8244. * @param eventData defines the data to send to all observers
  8245. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8246. * @param target defines the original target of the state
  8247. * @param currentTarget defines the current target of the state
  8248. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8249. */
  8250. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8251. if (mask === void 0) { mask = -1; }
  8252. if (!this._observers.length) {
  8253. return true;
  8254. }
  8255. var state = this._eventState;
  8256. state.mask = mask;
  8257. state.target = target;
  8258. state.currentTarget = currentTarget;
  8259. state.skipNextObservers = false;
  8260. state.lastReturnValue = eventData;
  8261. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8262. var obs = _a[_i];
  8263. if (obs._willBeUnregistered) {
  8264. continue;
  8265. }
  8266. if (obs.mask & mask) {
  8267. if (obs.scope) {
  8268. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8269. }
  8270. else {
  8271. state.lastReturnValue = obs.callback(eventData, state);
  8272. }
  8273. if (obs.unregisterOnNextCall) {
  8274. this._deferUnregister(obs);
  8275. }
  8276. }
  8277. if (state.skipNextObservers) {
  8278. return false;
  8279. }
  8280. }
  8281. return true;
  8282. };
  8283. /**
  8284. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8285. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8286. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8287. * and it is crucial that all callbacks will be executed.
  8288. * The order of the callbacks is kept, callbacks are not executed parallel.
  8289. *
  8290. * @param eventData The data to be sent to each callback
  8291. * @param mask is used to filter observers defaults to -1
  8292. * @param target defines the callback target (see EventState)
  8293. * @param currentTarget defines he current object in the bubbling phase
  8294. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8295. */
  8296. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8297. var _this = this;
  8298. if (mask === void 0) { mask = -1; }
  8299. // create an empty promise
  8300. var p = Promise.resolve(eventData);
  8301. // no observers? return this promise.
  8302. if (!this._observers.length) {
  8303. return p;
  8304. }
  8305. var state = this._eventState;
  8306. state.mask = mask;
  8307. state.target = target;
  8308. state.currentTarget = currentTarget;
  8309. state.skipNextObservers = false;
  8310. // execute one callback after another (not using Promise.all, the order is important)
  8311. this._observers.forEach(function (obs) {
  8312. if (state.skipNextObservers) {
  8313. return;
  8314. }
  8315. if (obs._willBeUnregistered) {
  8316. return;
  8317. }
  8318. if (obs.mask & mask) {
  8319. if (obs.scope) {
  8320. p = p.then(function (lastReturnedValue) {
  8321. state.lastReturnValue = lastReturnedValue;
  8322. return obs.callback.apply(obs.scope, [eventData, state]);
  8323. });
  8324. }
  8325. else {
  8326. p = p.then(function (lastReturnedValue) {
  8327. state.lastReturnValue = lastReturnedValue;
  8328. return obs.callback(eventData, state);
  8329. });
  8330. }
  8331. if (obs.unregisterOnNextCall) {
  8332. _this._deferUnregister(obs);
  8333. }
  8334. }
  8335. });
  8336. // return the eventData
  8337. return p.then(function () { return eventData; });
  8338. };
  8339. /**
  8340. * Notify a specific observer
  8341. * @param observer defines the observer to notify
  8342. * @param eventData defines the data to be sent to each callback
  8343. * @param mask is used to filter observers defaults to -1
  8344. */
  8345. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8346. if (mask === void 0) { mask = -1; }
  8347. var state = this._eventState;
  8348. state.mask = mask;
  8349. state.skipNextObservers = false;
  8350. observer.callback(eventData, state);
  8351. };
  8352. /**
  8353. * Gets a boolean indicating if the observable has at least one observer
  8354. * @returns true is the Observable has at least one Observer registered
  8355. */
  8356. Observable.prototype.hasObservers = function () {
  8357. return this._observers.length > 0;
  8358. };
  8359. /**
  8360. * Clear the list of observers
  8361. */
  8362. Observable.prototype.clear = function () {
  8363. this._observers = new Array();
  8364. this._onObserverAdded = null;
  8365. };
  8366. /**
  8367. * Clone the current observable
  8368. * @returns a new observable
  8369. */
  8370. Observable.prototype.clone = function () {
  8371. var result = new Observable();
  8372. result._observers = this._observers.slice(0);
  8373. return result;
  8374. };
  8375. /**
  8376. * Does this observable handles observer registered with a given mask
  8377. * @param mask defines the mask to be tested
  8378. * @return whether or not one observer registered with the given mask is handeled
  8379. **/
  8380. Observable.prototype.hasSpecificMask = function (mask) {
  8381. if (mask === void 0) { mask = -1; }
  8382. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8383. var obs = _a[_i];
  8384. if (obs.mask & mask || obs.mask === mask) {
  8385. return true;
  8386. }
  8387. }
  8388. return false;
  8389. };
  8390. return Observable;
  8391. }());
  8392. BABYLON.Observable = Observable;
  8393. })(BABYLON || (BABYLON = {}));
  8394. //# sourceMappingURL=babylon.observable.js.map
  8395. var BABYLON;
  8396. (function (BABYLON) {
  8397. var SmartArray = /** @class */ (function () {
  8398. function SmartArray(capacity) {
  8399. this.length = 0;
  8400. this.data = new Array(capacity);
  8401. this._id = SmartArray._GlobalId++;
  8402. }
  8403. SmartArray.prototype.push = function (value) {
  8404. this.data[this.length++] = value;
  8405. if (this.length > this.data.length) {
  8406. this.data.length *= 2;
  8407. }
  8408. };
  8409. SmartArray.prototype.forEach = function (func) {
  8410. for (var index = 0; index < this.length; index++) {
  8411. func(this.data[index]);
  8412. }
  8413. };
  8414. SmartArray.prototype.sort = function (compareFn) {
  8415. this.data.sort(compareFn);
  8416. };
  8417. SmartArray.prototype.reset = function () {
  8418. this.length = 0;
  8419. };
  8420. SmartArray.prototype.dispose = function () {
  8421. this.reset();
  8422. if (this.data) {
  8423. this.data.length = 0;
  8424. this.data = [];
  8425. }
  8426. };
  8427. SmartArray.prototype.concat = function (array) {
  8428. if (array.length === 0) {
  8429. return;
  8430. }
  8431. if (this.length + array.length > this.data.length) {
  8432. this.data.length = (this.length + array.length) * 2;
  8433. }
  8434. for (var index = 0; index < array.length; index++) {
  8435. this.data[this.length++] = (array.data || array)[index];
  8436. }
  8437. };
  8438. SmartArray.prototype.indexOf = function (value) {
  8439. var position = this.data.indexOf(value);
  8440. if (position >= this.length) {
  8441. return -1;
  8442. }
  8443. return position;
  8444. };
  8445. SmartArray.prototype.contains = function (value) {
  8446. return this.data.indexOf(value) !== -1;
  8447. };
  8448. // Statics
  8449. SmartArray._GlobalId = 0;
  8450. return SmartArray;
  8451. }());
  8452. BABYLON.SmartArray = SmartArray;
  8453. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8454. __extends(SmartArrayNoDuplicate, _super);
  8455. function SmartArrayNoDuplicate() {
  8456. var _this = _super !== null && _super.apply(this, arguments) || this;
  8457. _this._duplicateId = 0;
  8458. return _this;
  8459. }
  8460. SmartArrayNoDuplicate.prototype.push = function (value) {
  8461. _super.prototype.push.call(this, value);
  8462. if (!value.__smartArrayFlags) {
  8463. value.__smartArrayFlags = {};
  8464. }
  8465. value.__smartArrayFlags[this._id] = this._duplicateId;
  8466. };
  8467. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8468. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8469. return false;
  8470. }
  8471. this.push(value);
  8472. return true;
  8473. };
  8474. SmartArrayNoDuplicate.prototype.reset = function () {
  8475. _super.prototype.reset.call(this);
  8476. this._duplicateId++;
  8477. };
  8478. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8479. if (array.length === 0) {
  8480. return;
  8481. }
  8482. if (this.length + array.length > this.data.length) {
  8483. this.data.length = (this.length + array.length) * 2;
  8484. }
  8485. for (var index = 0; index < array.length; index++) {
  8486. var item = (array.data || array)[index];
  8487. this.pushNoDuplicate(item);
  8488. }
  8489. };
  8490. return SmartArrayNoDuplicate;
  8491. }(SmartArray));
  8492. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8493. })(BABYLON || (BABYLON = {}));
  8494. //# sourceMappingURL=babylon.smartArray.js.map
  8495. var BABYLON;
  8496. (function (BABYLON) {
  8497. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8498. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8499. var LoadFileError = /** @class */ (function (_super) {
  8500. __extends(LoadFileError, _super);
  8501. function LoadFileError(message, request) {
  8502. var _this = _super.call(this, message) || this;
  8503. _this.request = request;
  8504. _this.name = "LoadFileError";
  8505. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8506. return _this;
  8507. }
  8508. // Polyfill for Object.setPrototypeOf if necessary.
  8509. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8510. return LoadFileError;
  8511. }(Error));
  8512. BABYLON.LoadFileError = LoadFileError;
  8513. var RetryStrategy = /** @class */ (function () {
  8514. function RetryStrategy() {
  8515. }
  8516. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8517. if (maxRetries === void 0) { maxRetries = 3; }
  8518. if (baseInterval === void 0) { baseInterval = 500; }
  8519. return function (url, request, retryIndex) {
  8520. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8521. return -1;
  8522. }
  8523. return Math.pow(2, retryIndex) * baseInterval;
  8524. };
  8525. };
  8526. return RetryStrategy;
  8527. }());
  8528. BABYLON.RetryStrategy = RetryStrategy;
  8529. // Screenshots
  8530. var screenshotCanvas;
  8531. var cloneValue = function (source, destinationObject) {
  8532. if (!source)
  8533. return null;
  8534. if (source instanceof BABYLON.Mesh) {
  8535. return null;
  8536. }
  8537. if (source instanceof BABYLON.SubMesh) {
  8538. return source.clone(destinationObject);
  8539. }
  8540. else if (source.clone) {
  8541. return source.clone();
  8542. }
  8543. return null;
  8544. };
  8545. var Tools = /** @class */ (function () {
  8546. function Tools() {
  8547. }
  8548. /**
  8549. * Interpolates between a and b via alpha
  8550. * @param a The lower value (returned when alpha = 0)
  8551. * @param b The upper value (returned when alpha = 1)
  8552. * @param alpha The interpolation-factor
  8553. * @return The mixed value
  8554. */
  8555. Tools.Mix = function (a, b, alpha) {
  8556. return a * (1 - alpha) + b * alpha;
  8557. };
  8558. Tools.Instantiate = function (className) {
  8559. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8560. return Tools.RegisteredExternalClasses[className];
  8561. }
  8562. var arr = className.split(".");
  8563. var fn = (window || this);
  8564. for (var i = 0, len = arr.length; i < len; i++) {
  8565. fn = fn[arr[i]];
  8566. }
  8567. if (typeof fn !== "function") {
  8568. return null;
  8569. }
  8570. return fn;
  8571. };
  8572. /**
  8573. * Provides a slice function that will work even on IE
  8574. * @param data defines the array to slice
  8575. * @param start defines the start of the data (optional)
  8576. * @param end defines the end of the data (optional)
  8577. * @returns the new sliced array
  8578. */
  8579. Tools.Slice = function (data, start, end) {
  8580. if (data.slice) {
  8581. return data.slice(start, end);
  8582. }
  8583. return Array.prototype.slice.call(data, start, end);
  8584. };
  8585. Tools.SetImmediate = function (action) {
  8586. if (window.setImmediate) {
  8587. window.setImmediate(action);
  8588. }
  8589. else {
  8590. setTimeout(action, 1);
  8591. }
  8592. };
  8593. Tools.IsExponentOfTwo = function (value) {
  8594. var count = 1;
  8595. do {
  8596. count *= 2;
  8597. } while (count < value);
  8598. return count === value;
  8599. };
  8600. /**
  8601. * Returns the nearest 32-bit single precision float representation of a Number
  8602. * @param value A Number. If the parameter is of a different type, it will get converted
  8603. * to a number or to NaN if it cannot be converted
  8604. * @returns number
  8605. */
  8606. Tools.FloatRound = function (value) {
  8607. if (Math.fround) {
  8608. return Math.fround(value);
  8609. }
  8610. return (Tools._tmpFloatArray[0] = value);
  8611. };
  8612. /**
  8613. * Find the next highest power of two.
  8614. * @param x Number to start search from.
  8615. * @return Next highest power of two.
  8616. */
  8617. Tools.CeilingPOT = function (x) {
  8618. x--;
  8619. x |= x >> 1;
  8620. x |= x >> 2;
  8621. x |= x >> 4;
  8622. x |= x >> 8;
  8623. x |= x >> 16;
  8624. x++;
  8625. return x;
  8626. };
  8627. /**
  8628. * Find the next lowest power of two.
  8629. * @param x Number to start search from.
  8630. * @return Next lowest power of two.
  8631. */
  8632. Tools.FloorPOT = function (x) {
  8633. x = x | (x >> 1);
  8634. x = x | (x >> 2);
  8635. x = x | (x >> 4);
  8636. x = x | (x >> 8);
  8637. x = x | (x >> 16);
  8638. return x - (x >> 1);
  8639. };
  8640. /**
  8641. * Find the nearest power of two.
  8642. * @param x Number to start search from.
  8643. * @return Next nearest power of two.
  8644. */
  8645. Tools.NearestPOT = function (x) {
  8646. var c = Tools.CeilingPOT(x);
  8647. var f = Tools.FloorPOT(x);
  8648. return (c - x) > (x - f) ? f : c;
  8649. };
  8650. Tools.GetExponentOfTwo = function (value, max, mode) {
  8651. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8652. var pot;
  8653. switch (mode) {
  8654. case BABYLON.Engine.SCALEMODE_FLOOR:
  8655. pot = Tools.FloorPOT(value);
  8656. break;
  8657. case BABYLON.Engine.SCALEMODE_NEAREST:
  8658. pot = Tools.NearestPOT(value);
  8659. break;
  8660. case BABYLON.Engine.SCALEMODE_CEILING:
  8661. default:
  8662. pot = Tools.CeilingPOT(value);
  8663. break;
  8664. }
  8665. return Math.min(pot, max);
  8666. };
  8667. Tools.GetFilename = function (path) {
  8668. var index = path.lastIndexOf("/");
  8669. if (index < 0)
  8670. return path;
  8671. return path.substring(index + 1);
  8672. };
  8673. /**
  8674. * Extracts the "folder" part of a path (everything before the filename).
  8675. * @param uri The URI to extract the info from
  8676. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8677. * @returns The "folder" part of the path
  8678. */
  8679. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8680. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8681. var index = uri.lastIndexOf("/");
  8682. if (index < 0) {
  8683. if (returnUnchangedIfNoSlash) {
  8684. return uri;
  8685. }
  8686. return "";
  8687. }
  8688. return uri.substring(0, index + 1);
  8689. };
  8690. Tools.GetDOMTextContent = function (element) {
  8691. var result = "";
  8692. var child = element.firstChild;
  8693. while (child) {
  8694. if (child.nodeType === 3) {
  8695. result += child.textContent;
  8696. }
  8697. child = child.nextSibling;
  8698. }
  8699. return result;
  8700. };
  8701. Tools.ToDegrees = function (angle) {
  8702. return angle * 180 / Math.PI;
  8703. };
  8704. Tools.ToRadians = function (angle) {
  8705. return angle * Math.PI / 180;
  8706. };
  8707. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8708. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8709. var output = "";
  8710. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8711. var i = 0;
  8712. var bytes = new Uint8Array(buffer);
  8713. while (i < bytes.length) {
  8714. chr1 = bytes[i++];
  8715. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8716. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8717. enc1 = chr1 >> 2;
  8718. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8719. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8720. enc4 = chr3 & 63;
  8721. if (isNaN(chr2)) {
  8722. enc3 = enc4 = 64;
  8723. }
  8724. else if (isNaN(chr3)) {
  8725. enc4 = 64;
  8726. }
  8727. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8728. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8729. }
  8730. return "data:image/png;base64," + output;
  8731. };
  8732. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8733. if (bias === void 0) { bias = null; }
  8734. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8735. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8736. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8737. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8738. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8739. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8740. }
  8741. if (bias) {
  8742. minimum.x -= minimum.x * bias.x + bias.y;
  8743. minimum.y -= minimum.y * bias.x + bias.y;
  8744. minimum.z -= minimum.z * bias.x + bias.y;
  8745. maximum.x += maximum.x * bias.x + bias.y;
  8746. maximum.y += maximum.y * bias.x + bias.y;
  8747. maximum.z += maximum.z * bias.x + bias.y;
  8748. }
  8749. return {
  8750. minimum: minimum,
  8751. maximum: maximum
  8752. };
  8753. };
  8754. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8755. if (bias === void 0) { bias = null; }
  8756. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8757. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8758. if (!stride) {
  8759. stride = 3;
  8760. }
  8761. for (var index = start; index < start + count; index++) {
  8762. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8763. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8764. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8765. }
  8766. if (bias) {
  8767. minimum.x -= minimum.x * bias.x + bias.y;
  8768. minimum.y -= minimum.y * bias.x + bias.y;
  8769. minimum.z -= minimum.z * bias.x + bias.y;
  8770. maximum.x += maximum.x * bias.x + bias.y;
  8771. maximum.y += maximum.y * bias.x + bias.y;
  8772. maximum.z += maximum.z * bias.x + bias.y;
  8773. }
  8774. return {
  8775. minimum: minimum,
  8776. maximum: maximum
  8777. };
  8778. };
  8779. Tools.Vector2ArrayFeeder = function (array) {
  8780. return function (index) {
  8781. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8782. var length = isFloatArray ? array.length / 2 : array.length;
  8783. if (index >= length) {
  8784. return null;
  8785. }
  8786. if (isFloatArray) {
  8787. var fa = array;
  8788. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8789. }
  8790. var a = array;
  8791. return a[index];
  8792. };
  8793. };
  8794. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8795. if (bias === void 0) { bias = null; }
  8796. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8797. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8798. var i = 0;
  8799. var cur = feeder(i++);
  8800. while (cur) {
  8801. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8802. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8803. cur = feeder(i++);
  8804. }
  8805. if (bias) {
  8806. minimum.x -= minimum.x * bias.x + bias.y;
  8807. minimum.y -= minimum.y * bias.x + bias.y;
  8808. maximum.x += maximum.x * bias.x + bias.y;
  8809. maximum.y += maximum.y * bias.x + bias.y;
  8810. }
  8811. return {
  8812. minimum: minimum,
  8813. maximum: maximum
  8814. };
  8815. };
  8816. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8817. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8818. return null;
  8819. return Array.isArray(obj) ? obj : [obj];
  8820. };
  8821. // Misc.
  8822. Tools.GetPointerPrefix = function () {
  8823. var eventPrefix = "pointer";
  8824. // Check if pointer events are supported
  8825. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8826. eventPrefix = "mouse";
  8827. }
  8828. return eventPrefix;
  8829. };
  8830. /**
  8831. * @param func - the function to be called
  8832. * @param requester - the object that will request the next frame. Falls back to window.
  8833. */
  8834. Tools.QueueNewFrame = function (func, requester) {
  8835. if (!Tools.IsWindowObjectExist()) {
  8836. return setTimeout(func, 16);
  8837. }
  8838. if (!requester) {
  8839. requester = window;
  8840. }
  8841. if (requester.requestAnimationFrame) {
  8842. return requester.requestAnimationFrame(func);
  8843. }
  8844. else if (requester.msRequestAnimationFrame) {
  8845. return requester.msRequestAnimationFrame(func);
  8846. }
  8847. else if (requester.webkitRequestAnimationFrame) {
  8848. return requester.webkitRequestAnimationFrame(func);
  8849. }
  8850. else if (requester.mozRequestAnimationFrame) {
  8851. return requester.mozRequestAnimationFrame(func);
  8852. }
  8853. else if (requester.oRequestAnimationFrame) {
  8854. return requester.oRequestAnimationFrame(func);
  8855. }
  8856. else {
  8857. return window.setTimeout(func, 16);
  8858. }
  8859. };
  8860. Tools.RequestFullscreen = function (element) {
  8861. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8862. if (!requestFunction)
  8863. return;
  8864. requestFunction.call(element);
  8865. };
  8866. Tools.ExitFullscreen = function () {
  8867. if (document.exitFullscreen) {
  8868. document.exitFullscreen();
  8869. }
  8870. else if (document.mozCancelFullScreen) {
  8871. document.mozCancelFullScreen();
  8872. }
  8873. else if (document.webkitCancelFullScreen) {
  8874. document.webkitCancelFullScreen();
  8875. }
  8876. else if (document.msCancelFullScreen) {
  8877. document.msCancelFullScreen();
  8878. }
  8879. };
  8880. Tools.SetCorsBehavior = function (url, element) {
  8881. if (url && url.indexOf("data:") === 0) {
  8882. return;
  8883. }
  8884. if (Tools.CorsBehavior) {
  8885. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8886. element.crossOrigin = Tools.CorsBehavior;
  8887. }
  8888. else {
  8889. var result = Tools.CorsBehavior(url);
  8890. if (result) {
  8891. element.crossOrigin = result;
  8892. }
  8893. }
  8894. }
  8895. };
  8896. // External files
  8897. Tools.CleanUrl = function (url) {
  8898. url = url.replace(/#/mg, "%23");
  8899. return url;
  8900. };
  8901. /**
  8902. * Loads an image as an HTMLImageElement.
  8903. * @param input url string, ArrayBuffer, or Blob to load
  8904. * @param onLoad callback called when the image successfully loads
  8905. * @param onError callback called when the image fails to load
  8906. * @param database database for caching
  8907. * @returns the HTMLImageElement of the loaded image
  8908. */
  8909. Tools.LoadImage = function (input, onLoad, onError, database) {
  8910. var url;
  8911. var usingObjectURL = false;
  8912. if (input instanceof ArrayBuffer) {
  8913. url = URL.createObjectURL(new Blob([input]));
  8914. usingObjectURL = true;
  8915. }
  8916. else if (input instanceof Blob) {
  8917. url = URL.createObjectURL(input);
  8918. usingObjectURL = true;
  8919. }
  8920. else {
  8921. url = Tools.CleanUrl(input);
  8922. url = Tools.PreprocessUrl(input);
  8923. }
  8924. var img = new Image();
  8925. Tools.SetCorsBehavior(url, img);
  8926. var loadHandler = function () {
  8927. if (usingObjectURL && img.src) {
  8928. URL.revokeObjectURL(img.src);
  8929. }
  8930. img.removeEventListener("load", loadHandler);
  8931. img.removeEventListener("error", errorHandler);
  8932. onLoad(img);
  8933. };
  8934. var errorHandler = function (err) {
  8935. if (usingObjectURL && img.src) {
  8936. URL.revokeObjectURL(img.src);
  8937. }
  8938. img.removeEventListener("load", loadHandler);
  8939. img.removeEventListener("error", errorHandler);
  8940. Tools.Error("Error while trying to load image: " + input);
  8941. if (onError) {
  8942. onError("Error while trying to load image: " + input, err);
  8943. }
  8944. };
  8945. img.addEventListener("load", loadHandler);
  8946. img.addEventListener("error", errorHandler);
  8947. var noIndexedDB = function () {
  8948. img.src = url;
  8949. };
  8950. var loadFromIndexedDB = function () {
  8951. if (database) {
  8952. database.loadImageFromDB(url, img);
  8953. }
  8954. };
  8955. //ANY database to do!
  8956. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8957. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8958. }
  8959. else {
  8960. if (url.indexOf("file:") !== -1) {
  8961. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8962. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8963. try {
  8964. var blobURL;
  8965. try {
  8966. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8967. }
  8968. catch (ex) {
  8969. // Chrome doesn't support oneTimeOnly parameter
  8970. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8971. }
  8972. img.src = blobURL;
  8973. usingObjectURL = true;
  8974. }
  8975. catch (e) {
  8976. img.src = "";
  8977. }
  8978. return img;
  8979. }
  8980. }
  8981. noIndexedDB();
  8982. }
  8983. return img;
  8984. };
  8985. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8986. url = Tools.CleanUrl(url);
  8987. url = Tools.PreprocessUrl(url);
  8988. // If file and file input are set
  8989. if (url.indexOf("file:") !== -1) {
  8990. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8991. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8992. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8993. }
  8994. }
  8995. var loadUrl = Tools.BaseUrl + url;
  8996. var aborted = false;
  8997. var fileRequest = {
  8998. onCompleteObservable: new BABYLON.Observable(),
  8999. abort: function () { return aborted = true; },
  9000. };
  9001. var requestFile = function () {
  9002. var request = new XMLHttpRequest();
  9003. var retryHandle = null;
  9004. fileRequest.abort = function () {
  9005. aborted = true;
  9006. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9007. request.abort();
  9008. }
  9009. if (retryHandle !== null) {
  9010. clearTimeout(retryHandle);
  9011. retryHandle = null;
  9012. }
  9013. };
  9014. var retryLoop = function (retryIndex) {
  9015. request.open('GET', loadUrl, true);
  9016. if (useArrayBuffer) {
  9017. request.responseType = "arraybuffer";
  9018. }
  9019. if (onProgress) {
  9020. request.addEventListener("progress", onProgress);
  9021. }
  9022. var onLoadEnd = function () {
  9023. request.removeEventListener("loadend", onLoadEnd);
  9024. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9025. fileRequest.onCompleteObservable.clear();
  9026. };
  9027. request.addEventListener("loadend", onLoadEnd);
  9028. var onReadyStateChange = function () {
  9029. if (aborted) {
  9030. return;
  9031. }
  9032. // In case of undefined state in some browsers.
  9033. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9034. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9035. request.removeEventListener("readystatechange", onReadyStateChange);
  9036. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9037. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9038. return;
  9039. }
  9040. var retryStrategy = Tools.DefaultRetryStrategy;
  9041. if (retryStrategy) {
  9042. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9043. if (waitTime !== -1) {
  9044. // Prevent the request from completing for retry.
  9045. request.removeEventListener("loadend", onLoadEnd);
  9046. request = new XMLHttpRequest();
  9047. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9048. return;
  9049. }
  9050. }
  9051. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9052. if (onError) {
  9053. onError(request, e);
  9054. }
  9055. else {
  9056. throw e;
  9057. }
  9058. }
  9059. };
  9060. request.addEventListener("readystatechange", onReadyStateChange);
  9061. request.send();
  9062. };
  9063. retryLoop(0);
  9064. };
  9065. // Caching all files
  9066. if (database && database.enableSceneOffline) {
  9067. var noIndexedDB_1 = function () {
  9068. if (!aborted) {
  9069. requestFile();
  9070. }
  9071. };
  9072. var loadFromIndexedDB = function () {
  9073. // TODO: database needs to support aborting and should return a IFileRequest
  9074. if (aborted) {
  9075. return;
  9076. }
  9077. if (database) {
  9078. database.loadFileFromDB(url, function (data) {
  9079. if (!aborted) {
  9080. onSuccess(data);
  9081. }
  9082. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9083. }, onProgress ? function (event) {
  9084. if (!aborted) {
  9085. onProgress(event);
  9086. }
  9087. } : undefined, noIndexedDB_1, useArrayBuffer);
  9088. }
  9089. };
  9090. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9091. }
  9092. else {
  9093. requestFile();
  9094. }
  9095. return fileRequest;
  9096. };
  9097. /**
  9098. * Load a script (identified by an url). When the url returns, the
  9099. * content of this file is added into a new script element, attached to the DOM (body element)
  9100. */
  9101. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9102. var head = document.getElementsByTagName('head')[0];
  9103. var script = document.createElement('script');
  9104. script.type = 'text/javascript';
  9105. script.src = scriptUrl;
  9106. script.onload = function () {
  9107. if (onSuccess) {
  9108. onSuccess();
  9109. }
  9110. };
  9111. script.onerror = function (e) {
  9112. if (onError) {
  9113. onError("Unable to load script '" + scriptUrl + "'", e);
  9114. }
  9115. };
  9116. head.appendChild(script);
  9117. };
  9118. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9119. var reader = new FileReader();
  9120. var request = {
  9121. onCompleteObservable: new BABYLON.Observable(),
  9122. abort: function () { return reader.abort(); },
  9123. };
  9124. reader.onloadend = function (e) {
  9125. request.onCompleteObservable.notifyObservers(request);
  9126. };
  9127. reader.onload = function (e) {
  9128. //target doesn't have result from ts 1.3
  9129. callback(e.target['result']);
  9130. };
  9131. reader.onprogress = progressCallback;
  9132. reader.readAsDataURL(fileToLoad);
  9133. return request;
  9134. };
  9135. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9136. var reader = new FileReader();
  9137. var request = {
  9138. onCompleteObservable: new BABYLON.Observable(),
  9139. abort: function () { return reader.abort(); },
  9140. };
  9141. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9142. reader.onerror = function (e) {
  9143. Tools.Log("Error while reading file: " + fileToLoad.name);
  9144. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9145. };
  9146. reader.onload = function (e) {
  9147. //target doesn't have result from ts 1.3
  9148. callback(e.target['result']);
  9149. };
  9150. if (progressCallBack) {
  9151. reader.onprogress = progressCallBack;
  9152. }
  9153. if (!useArrayBuffer) {
  9154. // Asynchronous read
  9155. reader.readAsText(fileToLoad);
  9156. }
  9157. else {
  9158. reader.readAsArrayBuffer(fileToLoad);
  9159. }
  9160. return request;
  9161. };
  9162. //returns a downloadable url to a file content.
  9163. Tools.FileAsURL = function (content) {
  9164. var fileBlob = new Blob([content]);
  9165. var url = window.URL || window.webkitURL;
  9166. var link = url.createObjectURL(fileBlob);
  9167. return link;
  9168. };
  9169. // Misc.
  9170. Tools.Format = function (value, decimals) {
  9171. if (decimals === void 0) { decimals = 2; }
  9172. return value.toFixed(decimals);
  9173. };
  9174. Tools.CheckExtends = function (v, min, max) {
  9175. if (v.x < min.x)
  9176. min.x = v.x;
  9177. if (v.y < min.y)
  9178. min.y = v.y;
  9179. if (v.z < min.z)
  9180. min.z = v.z;
  9181. if (v.x > max.x)
  9182. max.x = v.x;
  9183. if (v.y > max.y)
  9184. max.y = v.y;
  9185. if (v.z > max.z)
  9186. max.z = v.z;
  9187. };
  9188. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9189. for (var prop in source) {
  9190. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9191. continue;
  9192. }
  9193. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9194. continue;
  9195. }
  9196. var sourceValue = source[prop];
  9197. var typeOfSourceValue = typeof sourceValue;
  9198. if (typeOfSourceValue === "function") {
  9199. continue;
  9200. }
  9201. try {
  9202. if (typeOfSourceValue === "object") {
  9203. if (sourceValue instanceof Array) {
  9204. destination[prop] = [];
  9205. if (sourceValue.length > 0) {
  9206. if (typeof sourceValue[0] == "object") {
  9207. for (var index = 0; index < sourceValue.length; index++) {
  9208. var clonedValue = cloneValue(sourceValue[index], destination);
  9209. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9210. destination[prop].push(clonedValue);
  9211. }
  9212. }
  9213. }
  9214. else {
  9215. destination[prop] = sourceValue.slice(0);
  9216. }
  9217. }
  9218. }
  9219. else {
  9220. destination[prop] = cloneValue(sourceValue, destination);
  9221. }
  9222. }
  9223. else {
  9224. destination[prop] = sourceValue;
  9225. }
  9226. }
  9227. catch (e) {
  9228. // Just ignore error (it could be because of a read-only property)
  9229. }
  9230. }
  9231. };
  9232. Tools.IsEmpty = function (obj) {
  9233. for (var i in obj) {
  9234. if (obj.hasOwnProperty(i)) {
  9235. return false;
  9236. }
  9237. }
  9238. return true;
  9239. };
  9240. Tools.RegisterTopRootEvents = function (events) {
  9241. for (var index = 0; index < events.length; index++) {
  9242. var event = events[index];
  9243. window.addEventListener(event.name, event.handler, false);
  9244. try {
  9245. if (window.parent) {
  9246. window.parent.addEventListener(event.name, event.handler, false);
  9247. }
  9248. }
  9249. catch (e) {
  9250. // Silently fails...
  9251. }
  9252. }
  9253. };
  9254. Tools.UnregisterTopRootEvents = function (events) {
  9255. for (var index = 0; index < events.length; index++) {
  9256. var event = events[index];
  9257. window.removeEventListener(event.name, event.handler);
  9258. try {
  9259. if (window.parent) {
  9260. window.parent.removeEventListener(event.name, event.handler);
  9261. }
  9262. }
  9263. catch (e) {
  9264. // Silently fails...
  9265. }
  9266. }
  9267. };
  9268. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9269. if (mimeType === void 0) { mimeType = "image/png"; }
  9270. // Read the contents of the framebuffer
  9271. var numberOfChannelsByLine = width * 4;
  9272. var halfHeight = height / 2;
  9273. //Reading datas from WebGL
  9274. var data = engine.readPixels(0, 0, width, height);
  9275. //To flip image on Y axis.
  9276. for (var i = 0; i < halfHeight; i++) {
  9277. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9278. var currentCell = j + i * numberOfChannelsByLine;
  9279. var targetLine = height - i - 1;
  9280. var targetCell = j + targetLine * numberOfChannelsByLine;
  9281. var temp = data[currentCell];
  9282. data[currentCell] = data[targetCell];
  9283. data[targetCell] = temp;
  9284. }
  9285. }
  9286. // Create a 2D canvas to store the result
  9287. if (!screenshotCanvas) {
  9288. screenshotCanvas = document.createElement('canvas');
  9289. }
  9290. screenshotCanvas.width = width;
  9291. screenshotCanvas.height = height;
  9292. var context = screenshotCanvas.getContext('2d');
  9293. if (context) {
  9294. // Copy the pixels to a 2D canvas
  9295. var imageData = context.createImageData(width, height);
  9296. var castData = (imageData.data);
  9297. castData.set(data);
  9298. context.putImageData(imageData, 0, 0);
  9299. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9300. }
  9301. };
  9302. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9303. if (mimeType === void 0) { mimeType = "image/png"; }
  9304. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9305. if (successCallback) {
  9306. successCallback(base64Image);
  9307. }
  9308. else {
  9309. // We need HTMLCanvasElement.toBlob for HD screenshots
  9310. if (!screenshotCanvas.toBlob) {
  9311. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9312. screenshotCanvas.toBlob = function (callback, type, quality) {
  9313. var _this = this;
  9314. setTimeout(function () {
  9315. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9316. for (var i = 0; i < len; i++) {
  9317. arr[i] = binStr.charCodeAt(i);
  9318. }
  9319. callback(new Blob([arr], { type: type || 'image/png' }));
  9320. });
  9321. };
  9322. }
  9323. screenshotCanvas.toBlob(function (blob) {
  9324. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9325. if (("download" in document.createElement("a"))) {
  9326. if (!fileName) {
  9327. var date = new Date();
  9328. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9329. fileName = "screenshot_" + stringDate + ".png";
  9330. }
  9331. Tools.Download(blob, fileName);
  9332. }
  9333. else {
  9334. var url = URL.createObjectURL(blob);
  9335. var newWindow = window.open("");
  9336. if (!newWindow)
  9337. return;
  9338. var img = newWindow.document.createElement("img");
  9339. img.onload = function () {
  9340. // no longer need to read the blob so it's revoked
  9341. URL.revokeObjectURL(url);
  9342. };
  9343. img.src = url;
  9344. newWindow.document.body.appendChild(img);
  9345. }
  9346. });
  9347. }
  9348. };
  9349. /**
  9350. * Downloads a blob in the browser
  9351. * @param blob defines the blob to download
  9352. * @param fileName defines the name of the downloaded file
  9353. */
  9354. Tools.Download = function (blob, fileName) {
  9355. var url = window.URL.createObjectURL(blob);
  9356. var a = document.createElement("a");
  9357. document.body.appendChild(a);
  9358. a.style.display = "none";
  9359. a.href = url;
  9360. a.download = fileName;
  9361. a.addEventListener("click", function () {
  9362. if (a.parentElement) {
  9363. a.parentElement.removeChild(a);
  9364. }
  9365. });
  9366. a.click();
  9367. window.URL.revokeObjectURL(url);
  9368. };
  9369. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9370. if (mimeType === void 0) { mimeType = "image/png"; }
  9371. var width;
  9372. var height;
  9373. // If a precision value is specified
  9374. if (size.precision) {
  9375. width = Math.round(engine.getRenderWidth() * size.precision);
  9376. height = Math.round(width / engine.getAspectRatio(camera));
  9377. }
  9378. else if (size.width && size.height) {
  9379. width = size.width;
  9380. height = size.height;
  9381. }
  9382. //If passing only width, computing height to keep display canvas ratio.
  9383. else if (size.width && !size.height) {
  9384. width = size.width;
  9385. height = Math.round(width / engine.getAspectRatio(camera));
  9386. }
  9387. //If passing only height, computing width to keep display canvas ratio.
  9388. else if (size.height && !size.width) {
  9389. height = size.height;
  9390. width = Math.round(height * engine.getAspectRatio(camera));
  9391. }
  9392. //Assuming here that "size" parameter is a number
  9393. else if (!isNaN(size)) {
  9394. height = size;
  9395. width = size;
  9396. }
  9397. else {
  9398. Tools.Error("Invalid 'size' parameter !");
  9399. return;
  9400. }
  9401. if (!screenshotCanvas) {
  9402. screenshotCanvas = document.createElement('canvas');
  9403. }
  9404. screenshotCanvas.width = width;
  9405. screenshotCanvas.height = height;
  9406. var renderContext = screenshotCanvas.getContext("2d");
  9407. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9408. var newWidth = width;
  9409. var newHeight = newWidth / ratio;
  9410. if (newHeight > height) {
  9411. newHeight = height;
  9412. newWidth = newHeight * ratio;
  9413. }
  9414. var offsetX = Math.max(0, width - newWidth) / 2;
  9415. var offsetY = Math.max(0, height - newHeight) / 2;
  9416. var renderingCanvas = engine.getRenderingCanvas();
  9417. if (renderContext && renderingCanvas) {
  9418. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9419. }
  9420. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9421. };
  9422. /**
  9423. * Generates an image screenshot from the specified camera.
  9424. *
  9425. * @param engine The engine to use for rendering
  9426. * @param camera The camera to use for rendering
  9427. * @param size This parameter can be set to a single number or to an object with the
  9428. * following (optional) properties: precision, width, height. If a single number is passed,
  9429. * it will be used for both width and height. If an object is passed, the screenshot size
  9430. * will be derived from the parameters. The precision property is a multiplier allowing
  9431. * rendering at a higher or lower resolution.
  9432. * @param successCallback The callback receives a single parameter which contains the
  9433. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9434. * src parameter of an <img> to display it.
  9435. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9436. * Check your browser for supported MIME types.
  9437. * @param samples Texture samples (default: 1)
  9438. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9439. * @param fileName A name for for the downloaded file.
  9440. * @constructor
  9441. */
  9442. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9443. if (mimeType === void 0) { mimeType = "image/png"; }
  9444. if (samples === void 0) { samples = 1; }
  9445. if (antialiasing === void 0) { antialiasing = false; }
  9446. var width;
  9447. var height;
  9448. //If a precision value is specified
  9449. if (size.precision) {
  9450. width = Math.round(engine.getRenderWidth() * size.precision);
  9451. height = Math.round(width / engine.getAspectRatio(camera));
  9452. size = { width: width, height: height };
  9453. }
  9454. else if (size.width && size.height) {
  9455. width = size.width;
  9456. height = size.height;
  9457. }
  9458. //If passing only width, computing height to keep display canvas ratio.
  9459. else if (size.width && !size.height) {
  9460. width = size.width;
  9461. height = Math.round(width / engine.getAspectRatio(camera));
  9462. size = { width: width, height: height };
  9463. }
  9464. //If passing only height, computing width to keep display canvas ratio.
  9465. else if (size.height && !size.width) {
  9466. height = size.height;
  9467. width = Math.round(height * engine.getAspectRatio(camera));
  9468. size = { width: width, height: height };
  9469. }
  9470. //Assuming here that "size" parameter is a number
  9471. else if (!isNaN(size)) {
  9472. height = size;
  9473. width = size;
  9474. }
  9475. else {
  9476. Tools.Error("Invalid 'size' parameter !");
  9477. return;
  9478. }
  9479. var scene = camera.getScene();
  9480. var previousCamera = null;
  9481. if (scene.activeCamera !== camera) {
  9482. previousCamera = scene.activeCamera;
  9483. scene.activeCamera = camera;
  9484. }
  9485. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9486. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9487. texture.renderList = null;
  9488. texture.samples = samples;
  9489. if (antialiasing) {
  9490. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9491. }
  9492. texture.onAfterRenderObservable.add(function () {
  9493. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9494. });
  9495. scene.incrementRenderId();
  9496. scene.resetCachedMaterial();
  9497. texture.render(true);
  9498. texture.dispose();
  9499. if (previousCamera) {
  9500. scene.activeCamera = previousCamera;
  9501. }
  9502. camera.getProjectionMatrix(true); // Force cache refresh;
  9503. };
  9504. // XHR response validator for local file scenario
  9505. Tools.ValidateXHRData = function (xhr, dataType) {
  9506. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9507. if (dataType === void 0) { dataType = 7; }
  9508. try {
  9509. if (dataType & 1) {
  9510. if (xhr.responseText && xhr.responseText.length > 0) {
  9511. return true;
  9512. }
  9513. else if (dataType === 1) {
  9514. return false;
  9515. }
  9516. }
  9517. if (dataType & 2) {
  9518. // Check header width and height since there is no "TGA" magic number
  9519. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9520. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9521. return true;
  9522. }
  9523. else if (dataType === 2) {
  9524. return false;
  9525. }
  9526. }
  9527. if (dataType & 4) {
  9528. // Check for the "DDS" magic number
  9529. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9530. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9531. return true;
  9532. }
  9533. else {
  9534. return false;
  9535. }
  9536. }
  9537. }
  9538. catch (e) {
  9539. // Global protection
  9540. }
  9541. return false;
  9542. };
  9543. /**
  9544. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9545. * Be aware Math.random() could cause collisions, but:
  9546. * "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"
  9547. */
  9548. Tools.RandomId = function () {
  9549. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9550. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9551. return v.toString(16);
  9552. });
  9553. };
  9554. /**
  9555. * Test if the given uri is a base64 string.
  9556. * @param uri The uri to test
  9557. * @return True if the uri is a base64 string or false otherwise.
  9558. */
  9559. Tools.IsBase64 = function (uri) {
  9560. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9561. };
  9562. /**
  9563. * Decode the given base64 uri.
  9564. * @param uri The uri to decode
  9565. * @return The decoded base64 data.
  9566. */
  9567. Tools.DecodeBase64 = function (uri) {
  9568. var decodedString = atob(uri.split(",")[1]);
  9569. var bufferLength = decodedString.length;
  9570. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9571. for (var i = 0; i < bufferLength; i++) {
  9572. bufferView[i] = decodedString.charCodeAt(i);
  9573. }
  9574. return bufferView.buffer;
  9575. };
  9576. Object.defineProperty(Tools, "NoneLogLevel", {
  9577. get: function () {
  9578. return Tools._NoneLogLevel;
  9579. },
  9580. enumerable: true,
  9581. configurable: true
  9582. });
  9583. Object.defineProperty(Tools, "MessageLogLevel", {
  9584. get: function () {
  9585. return Tools._MessageLogLevel;
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(Tools, "WarningLogLevel", {
  9591. get: function () {
  9592. return Tools._WarningLogLevel;
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Object.defineProperty(Tools, "ErrorLogLevel", {
  9598. get: function () {
  9599. return Tools._ErrorLogLevel;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. Object.defineProperty(Tools, "AllLogLevel", {
  9605. get: function () {
  9606. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9607. },
  9608. enumerable: true,
  9609. configurable: true
  9610. });
  9611. Tools._AddLogEntry = function (entry) {
  9612. Tools._LogCache = entry + Tools._LogCache;
  9613. if (Tools.OnNewCacheEntry) {
  9614. Tools.OnNewCacheEntry(entry);
  9615. }
  9616. };
  9617. Tools._FormatMessage = function (message) {
  9618. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9619. var date = new Date();
  9620. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9621. };
  9622. Tools._LogDisabled = function (message) {
  9623. // nothing to do
  9624. };
  9625. Tools._LogEnabled = function (message) {
  9626. var formattedMessage = Tools._FormatMessage(message);
  9627. console.log("BJS - " + formattedMessage);
  9628. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9629. Tools._AddLogEntry(entry);
  9630. };
  9631. Tools._WarnDisabled = function (message) {
  9632. // nothing to do
  9633. };
  9634. Tools._WarnEnabled = function (message) {
  9635. var formattedMessage = Tools._FormatMessage(message);
  9636. console.warn("BJS - " + formattedMessage);
  9637. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9638. Tools._AddLogEntry(entry);
  9639. };
  9640. Tools._ErrorDisabled = function (message) {
  9641. // nothing to do
  9642. };
  9643. Tools._ErrorEnabled = function (message) {
  9644. Tools.errorsCount++;
  9645. var formattedMessage = Tools._FormatMessage(message);
  9646. console.error("BJS - " + formattedMessage);
  9647. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9648. Tools._AddLogEntry(entry);
  9649. };
  9650. Object.defineProperty(Tools, "LogCache", {
  9651. get: function () {
  9652. return Tools._LogCache;
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. Tools.ClearLogCache = function () {
  9658. Tools._LogCache = "";
  9659. Tools.errorsCount = 0;
  9660. };
  9661. Object.defineProperty(Tools, "LogLevels", {
  9662. set: function (level) {
  9663. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9664. Tools.Log = Tools._LogEnabled;
  9665. }
  9666. else {
  9667. Tools.Log = Tools._LogDisabled;
  9668. }
  9669. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9670. Tools.Warn = Tools._WarnEnabled;
  9671. }
  9672. else {
  9673. Tools.Warn = Tools._WarnDisabled;
  9674. }
  9675. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9676. Tools.Error = Tools._ErrorEnabled;
  9677. }
  9678. else {
  9679. Tools.Error = Tools._ErrorDisabled;
  9680. }
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Tools.IsWindowObjectExist = function () {
  9686. return (typeof window) !== "undefined";
  9687. };
  9688. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9689. get: function () {
  9690. return Tools._PerformanceNoneLogLevel;
  9691. },
  9692. enumerable: true,
  9693. configurable: true
  9694. });
  9695. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9696. get: function () {
  9697. return Tools._PerformanceUserMarkLogLevel;
  9698. },
  9699. enumerable: true,
  9700. configurable: true
  9701. });
  9702. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9703. get: function () {
  9704. return Tools._PerformanceConsoleLogLevel;
  9705. },
  9706. enumerable: true,
  9707. configurable: true
  9708. });
  9709. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9710. set: function (level) {
  9711. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9712. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9713. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9714. return;
  9715. }
  9716. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9717. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9718. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9719. return;
  9720. }
  9721. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9722. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9723. },
  9724. enumerable: true,
  9725. configurable: true
  9726. });
  9727. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9728. };
  9729. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9730. };
  9731. Tools._StartUserMark = function (counterName, condition) {
  9732. if (condition === void 0) { condition = true; }
  9733. if (!Tools._performance) {
  9734. if (!Tools.IsWindowObjectExist()) {
  9735. return;
  9736. }
  9737. Tools._performance = window.performance;
  9738. }
  9739. if (!condition || !Tools._performance.mark) {
  9740. return;
  9741. }
  9742. Tools._performance.mark(counterName + "-Begin");
  9743. };
  9744. Tools._EndUserMark = function (counterName, condition) {
  9745. if (condition === void 0) { condition = true; }
  9746. if (!condition || !Tools._performance.mark) {
  9747. return;
  9748. }
  9749. Tools._performance.mark(counterName + "-End");
  9750. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9751. };
  9752. Tools._StartPerformanceConsole = function (counterName, condition) {
  9753. if (condition === void 0) { condition = true; }
  9754. if (!condition) {
  9755. return;
  9756. }
  9757. Tools._StartUserMark(counterName, condition);
  9758. if (console.time) {
  9759. console.time(counterName);
  9760. }
  9761. };
  9762. Tools._EndPerformanceConsole = function (counterName, condition) {
  9763. if (condition === void 0) { condition = true; }
  9764. if (!condition) {
  9765. return;
  9766. }
  9767. Tools._EndUserMark(counterName, condition);
  9768. if (console.time) {
  9769. console.timeEnd(counterName);
  9770. }
  9771. };
  9772. Object.defineProperty(Tools, "Now", {
  9773. get: function () {
  9774. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9775. return window.performance.now();
  9776. }
  9777. return Date.now();
  9778. },
  9779. enumerable: true,
  9780. configurable: true
  9781. });
  9782. /**
  9783. * This method will return the name of the class used to create the instance of the given object.
  9784. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9785. * @param object the object to get the class name from
  9786. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9787. */
  9788. Tools.GetClassName = function (object, isType) {
  9789. if (isType === void 0) { isType = false; }
  9790. var name = null;
  9791. if (!isType && object.getClassName) {
  9792. name = object.getClassName();
  9793. }
  9794. else {
  9795. if (object instanceof Object) {
  9796. var classObj = isType ? object : Object.getPrototypeOf(object);
  9797. name = classObj.constructor["__bjsclassName__"];
  9798. }
  9799. if (!name) {
  9800. name = typeof object;
  9801. }
  9802. }
  9803. return name;
  9804. };
  9805. Tools.First = function (array, predicate) {
  9806. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9807. var el = array_1[_i];
  9808. if (predicate(el)) {
  9809. return el;
  9810. }
  9811. }
  9812. return null;
  9813. };
  9814. /**
  9815. * This method will return the name of the full name of the class, including its owning module (if any).
  9816. * 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).
  9817. * @param object the object to get the class name from
  9818. * @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.
  9819. */
  9820. Tools.getFullClassName = function (object, isType) {
  9821. if (isType === void 0) { isType = false; }
  9822. var className = null;
  9823. var moduleName = null;
  9824. if (!isType && object.getClassName) {
  9825. className = object.getClassName();
  9826. }
  9827. else {
  9828. if (object instanceof Object) {
  9829. var classObj = isType ? object : Object.getPrototypeOf(object);
  9830. className = classObj.constructor["__bjsclassName__"];
  9831. moduleName = classObj.constructor["__bjsmoduleName__"];
  9832. }
  9833. if (!className) {
  9834. className = typeof object;
  9835. }
  9836. }
  9837. if (!className) {
  9838. return null;
  9839. }
  9840. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9841. };
  9842. /**
  9843. * 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.
  9844. * @param array
  9845. */
  9846. Tools.arrayOrStringFeeder = function (array) {
  9847. return function (index) {
  9848. if (index >= array.length) {
  9849. return null;
  9850. }
  9851. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9852. if (val && val.getHashCode) {
  9853. val = val.getHashCode();
  9854. }
  9855. if (typeof val === "string") {
  9856. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9857. }
  9858. return val;
  9859. };
  9860. };
  9861. /**
  9862. * Compute the hashCode of a stream of number
  9863. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9864. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9865. * @return the hash code computed
  9866. */
  9867. Tools.hashCodeFromStream = function (feeder) {
  9868. // Based from here: http://stackoverflow.com/a/7616484/802124
  9869. var hash = 0;
  9870. var index = 0;
  9871. var chr = feeder(index++);
  9872. while (chr != null) {
  9873. hash = ((hash << 5) - hash) + chr;
  9874. hash |= 0; // Convert to 32bit integer
  9875. chr = feeder(index++);
  9876. }
  9877. return hash;
  9878. };
  9879. /**
  9880. * Returns a promise that resolves after the given amount of time.
  9881. * @param delay Number of milliseconds to delay
  9882. * @returns Promise that resolves after the given amount of time
  9883. */
  9884. Tools.DelayAsync = function (delay) {
  9885. return new Promise(function (resolve) {
  9886. setTimeout(function () {
  9887. resolve();
  9888. }, delay);
  9889. });
  9890. };
  9891. Tools.BaseUrl = "";
  9892. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9893. /**
  9894. * Default behaviour for cors in the application.
  9895. * It can be a string if the expected behavior is identical in the entire app.
  9896. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9897. */
  9898. Tools.CorsBehavior = "anonymous";
  9899. Tools.UseFallbackTexture = true;
  9900. /**
  9901. * Use this object to register external classes like custom textures or material
  9902. * to allow the laoders to instantiate them
  9903. */
  9904. Tools.RegisteredExternalClasses = {};
  9905. // Used in case of a texture loading problem
  9906. 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";
  9907. Tools._tmpFloatArray = new Float32Array(1);
  9908. Tools.PreprocessUrl = function (url) {
  9909. return url;
  9910. };
  9911. // Logs
  9912. Tools._NoneLogLevel = 0;
  9913. Tools._MessageLogLevel = 1;
  9914. Tools._WarningLogLevel = 2;
  9915. Tools._ErrorLogLevel = 4;
  9916. Tools._LogCache = "";
  9917. Tools.errorsCount = 0;
  9918. Tools.Log = Tools._LogEnabled;
  9919. Tools.Warn = Tools._WarnEnabled;
  9920. Tools.Error = Tools._ErrorEnabled;
  9921. // Performances
  9922. Tools._PerformanceNoneLogLevel = 0;
  9923. Tools._PerformanceUserMarkLogLevel = 1;
  9924. Tools._PerformanceConsoleLogLevel = 2;
  9925. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9926. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9927. return Tools;
  9928. }());
  9929. BABYLON.Tools = Tools;
  9930. /**
  9931. * This class is used to track a performance counter which is number based.
  9932. * The user has access to many properties which give statistics of different nature
  9933. *
  9934. * The implementer can track two kinds of Performance Counter: time and count
  9935. * 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.
  9936. * 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.
  9937. */
  9938. var PerfCounter = /** @class */ (function () {
  9939. function PerfCounter() {
  9940. this._startMonitoringTime = 0;
  9941. this._min = 0;
  9942. this._max = 0;
  9943. this._average = 0;
  9944. this._lastSecAverage = 0;
  9945. this._current = 0;
  9946. this._totalValueCount = 0;
  9947. this._totalAccumulated = 0;
  9948. this._lastSecAccumulated = 0;
  9949. this._lastSecTime = 0;
  9950. this._lastSecValueCount = 0;
  9951. }
  9952. Object.defineProperty(PerfCounter.prototype, "min", {
  9953. /**
  9954. * Returns the smallest value ever
  9955. */
  9956. get: function () {
  9957. return this._min;
  9958. },
  9959. enumerable: true,
  9960. configurable: true
  9961. });
  9962. Object.defineProperty(PerfCounter.prototype, "max", {
  9963. /**
  9964. * Returns the biggest value ever
  9965. */
  9966. get: function () {
  9967. return this._max;
  9968. },
  9969. enumerable: true,
  9970. configurable: true
  9971. });
  9972. Object.defineProperty(PerfCounter.prototype, "average", {
  9973. /**
  9974. * Returns the average value since the performance counter is running
  9975. */
  9976. get: function () {
  9977. return this._average;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9983. /**
  9984. * Returns the average value of the last second the counter was monitored
  9985. */
  9986. get: function () {
  9987. return this._lastSecAverage;
  9988. },
  9989. enumerable: true,
  9990. configurable: true
  9991. });
  9992. Object.defineProperty(PerfCounter.prototype, "current", {
  9993. /**
  9994. * Returns the current value
  9995. */
  9996. get: function () {
  9997. return this._current;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. Object.defineProperty(PerfCounter.prototype, "total", {
  10003. get: function () {
  10004. return this._totalAccumulated;
  10005. },
  10006. enumerable: true,
  10007. configurable: true
  10008. });
  10009. Object.defineProperty(PerfCounter.prototype, "count", {
  10010. get: function () {
  10011. return this._totalValueCount;
  10012. },
  10013. enumerable: true,
  10014. configurable: true
  10015. });
  10016. /**
  10017. * Call this method to start monitoring a new frame.
  10018. * 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.
  10019. */
  10020. PerfCounter.prototype.fetchNewFrame = function () {
  10021. this._totalValueCount++;
  10022. this._current = 0;
  10023. this._lastSecValueCount++;
  10024. };
  10025. /**
  10026. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10027. * @param newCount the count value to add to the monitored count
  10028. * @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.
  10029. */
  10030. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10031. if (!PerfCounter.Enabled) {
  10032. return;
  10033. }
  10034. this._current += newCount;
  10035. if (fetchResult) {
  10036. this._fetchResult();
  10037. }
  10038. };
  10039. /**
  10040. * Start monitoring this performance counter
  10041. */
  10042. PerfCounter.prototype.beginMonitoring = function () {
  10043. if (!PerfCounter.Enabled) {
  10044. return;
  10045. }
  10046. this._startMonitoringTime = Tools.Now;
  10047. };
  10048. /**
  10049. * Compute the time lapsed since the previous beginMonitoring() call.
  10050. * @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
  10051. */
  10052. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10053. if (newFrame === void 0) { newFrame = true; }
  10054. if (!PerfCounter.Enabled) {
  10055. return;
  10056. }
  10057. if (newFrame) {
  10058. this.fetchNewFrame();
  10059. }
  10060. var currentTime = Tools.Now;
  10061. this._current = currentTime - this._startMonitoringTime;
  10062. if (newFrame) {
  10063. this._fetchResult();
  10064. }
  10065. };
  10066. PerfCounter.prototype._fetchResult = function () {
  10067. this._totalAccumulated += this._current;
  10068. this._lastSecAccumulated += this._current;
  10069. // Min/Max update
  10070. this._min = Math.min(this._min, this._current);
  10071. this._max = Math.max(this._max, this._current);
  10072. this._average = this._totalAccumulated / this._totalValueCount;
  10073. // Reset last sec?
  10074. var now = Tools.Now;
  10075. if ((now - this._lastSecTime) > 1000) {
  10076. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10077. this._lastSecTime = now;
  10078. this._lastSecAccumulated = 0;
  10079. this._lastSecValueCount = 0;
  10080. }
  10081. };
  10082. PerfCounter.Enabled = true;
  10083. return PerfCounter;
  10084. }());
  10085. BABYLON.PerfCounter = PerfCounter;
  10086. /**
  10087. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10088. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10089. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10090. * @param name The name of the class, case should be preserved
  10091. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10092. */
  10093. function className(name, module) {
  10094. return function (target) {
  10095. target["__bjsclassName__"] = name;
  10096. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10097. };
  10098. }
  10099. BABYLON.className = className;
  10100. /**
  10101. * An implementation of a loop for asynchronous functions.
  10102. */
  10103. var AsyncLoop = /** @class */ (function () {
  10104. /**
  10105. * Constroctor.
  10106. * @param iterations the number of iterations.
  10107. * @param _fn the function to run each iteration
  10108. * @param _successCallback the callback that will be called upon succesful execution
  10109. * @param offset starting offset.
  10110. */
  10111. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10112. if (offset === void 0) { offset = 0; }
  10113. this.iterations = iterations;
  10114. this._fn = _fn;
  10115. this._successCallback = _successCallback;
  10116. this.index = offset - 1;
  10117. this._done = false;
  10118. }
  10119. /**
  10120. * Execute the next iteration. Must be called after the last iteration was finished.
  10121. */
  10122. AsyncLoop.prototype.executeNext = function () {
  10123. if (!this._done) {
  10124. if (this.index + 1 < this.iterations) {
  10125. ++this.index;
  10126. this._fn(this);
  10127. }
  10128. else {
  10129. this.breakLoop();
  10130. }
  10131. }
  10132. };
  10133. /**
  10134. * Break the loop and run the success callback.
  10135. */
  10136. AsyncLoop.prototype.breakLoop = function () {
  10137. this._done = true;
  10138. this._successCallback();
  10139. };
  10140. /**
  10141. * Helper function
  10142. */
  10143. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10144. if (offset === void 0) { offset = 0; }
  10145. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10146. loop.executeNext();
  10147. return loop;
  10148. };
  10149. /**
  10150. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10151. * @param iterations total number of iterations
  10152. * @param syncedIterations number of synchronous iterations in each async iteration.
  10153. * @param fn the function to call each iteration.
  10154. * @param callback a success call back that will be called when iterating stops.
  10155. * @param breakFunction a break condition (optional)
  10156. * @param timeout timeout settings for the setTimeout function. default - 0.
  10157. * @constructor
  10158. */
  10159. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10160. if (timeout === void 0) { timeout = 0; }
  10161. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10162. if (breakFunction && breakFunction())
  10163. loop.breakLoop();
  10164. else {
  10165. setTimeout(function () {
  10166. for (var i = 0; i < syncedIterations; ++i) {
  10167. var iteration = (loop.index * syncedIterations) + i;
  10168. if (iteration >= iterations)
  10169. break;
  10170. fn(iteration);
  10171. if (breakFunction && breakFunction()) {
  10172. loop.breakLoop();
  10173. break;
  10174. }
  10175. }
  10176. loop.executeNext();
  10177. }, timeout);
  10178. }
  10179. }, callback);
  10180. };
  10181. return AsyncLoop;
  10182. }());
  10183. BABYLON.AsyncLoop = AsyncLoop;
  10184. })(BABYLON || (BABYLON = {}));
  10185. //# sourceMappingURL=babylon.tools.js.map
  10186. var BABYLON;
  10187. (function (BABYLON) {
  10188. var PromiseStates;
  10189. (function (PromiseStates) {
  10190. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10191. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10192. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10193. })(PromiseStates || (PromiseStates = {}));
  10194. var FulFillmentAgregator = /** @class */ (function () {
  10195. function FulFillmentAgregator() {
  10196. this.count = 0;
  10197. this.target = 0;
  10198. this.results = [];
  10199. }
  10200. return FulFillmentAgregator;
  10201. }());
  10202. var InternalPromise = /** @class */ (function () {
  10203. function InternalPromise(resolver) {
  10204. var _this = this;
  10205. this._state = PromiseStates.Pending;
  10206. this._children = new Array();
  10207. this._rejectWasConsumed = false;
  10208. if (!resolver) {
  10209. return;
  10210. }
  10211. try {
  10212. resolver(function (value) {
  10213. _this._resolve(value);
  10214. }, function (reason) {
  10215. _this._reject(reason);
  10216. });
  10217. }
  10218. catch (e) {
  10219. this._reject(e);
  10220. }
  10221. }
  10222. Object.defineProperty(InternalPromise.prototype, "_result", {
  10223. get: function () {
  10224. return this._resultValue;
  10225. },
  10226. set: function (value) {
  10227. this._resultValue = value;
  10228. if (this._parent && this._parent._result === undefined) {
  10229. this._parent._result = value;
  10230. }
  10231. },
  10232. enumerable: true,
  10233. configurable: true
  10234. });
  10235. InternalPromise.prototype.catch = function (onRejected) {
  10236. return this.then(undefined, onRejected);
  10237. };
  10238. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10239. var _this = this;
  10240. var newPromise = new InternalPromise();
  10241. newPromise._onFulfilled = onFulfilled;
  10242. newPromise._onRejected = onRejected;
  10243. // Composition
  10244. this._children.push(newPromise);
  10245. newPromise._parent = this;
  10246. if (this._state !== PromiseStates.Pending) {
  10247. BABYLON.Tools.SetImmediate(function () {
  10248. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10249. var returnedValue = newPromise._resolve(_this._result);
  10250. if (returnedValue !== undefined && returnedValue !== null) {
  10251. if (returnedValue._state !== undefined) {
  10252. var returnedPromise = returnedValue;
  10253. newPromise._children.push(returnedPromise);
  10254. returnedPromise._parent = newPromise;
  10255. newPromise = returnedPromise;
  10256. }
  10257. else {
  10258. newPromise._result = returnedValue;
  10259. }
  10260. }
  10261. }
  10262. else {
  10263. newPromise._reject(_this._reason);
  10264. }
  10265. });
  10266. }
  10267. return newPromise;
  10268. };
  10269. InternalPromise.prototype._moveChildren = function (children) {
  10270. var _this = this;
  10271. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10272. this._children.forEach(function (child) {
  10273. child._parent = _this;
  10274. });
  10275. if (this._state === PromiseStates.Fulfilled) {
  10276. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10277. var child = _b[_i];
  10278. child._resolve(this._result);
  10279. }
  10280. }
  10281. else if (this._state === PromiseStates.Rejected) {
  10282. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10283. var child = _d[_c];
  10284. child._reject(this._reason);
  10285. }
  10286. }
  10287. var _a;
  10288. };
  10289. InternalPromise.prototype._resolve = function (value) {
  10290. try {
  10291. this._state = PromiseStates.Fulfilled;
  10292. var returnedValue = null;
  10293. if (this._onFulfilled) {
  10294. returnedValue = this._onFulfilled(value);
  10295. }
  10296. if (returnedValue !== undefined && returnedValue !== null) {
  10297. if (returnedValue._state !== undefined) {
  10298. // Transmit children
  10299. var returnedPromise = returnedValue;
  10300. returnedPromise._parent = this;
  10301. returnedPromise._moveChildren(this._children);
  10302. value = returnedPromise._result;
  10303. }
  10304. else {
  10305. value = returnedValue;
  10306. }
  10307. }
  10308. this._result = value;
  10309. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10310. var child = _a[_i];
  10311. child._resolve(value);
  10312. }
  10313. this._children.length = 0;
  10314. delete this._onFulfilled;
  10315. delete this._onRejected;
  10316. }
  10317. catch (e) {
  10318. this._reject(e, true);
  10319. }
  10320. };
  10321. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10322. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10323. this._state = PromiseStates.Rejected;
  10324. this._reason = reason;
  10325. if (this._onRejected && !onLocalThrow) {
  10326. try {
  10327. this._onRejected(reason);
  10328. this._rejectWasConsumed = true;
  10329. }
  10330. catch (e) {
  10331. reason = e;
  10332. }
  10333. }
  10334. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10335. var child = _a[_i];
  10336. if (this._rejectWasConsumed) {
  10337. child._resolve(null);
  10338. }
  10339. else {
  10340. child._reject(reason);
  10341. }
  10342. }
  10343. this._children.length = 0;
  10344. delete this._onFulfilled;
  10345. delete this._onRejected;
  10346. };
  10347. InternalPromise.resolve = function (value) {
  10348. var newPromise = new InternalPromise();
  10349. newPromise._resolve(value);
  10350. return newPromise;
  10351. };
  10352. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10353. promise.then(function (value) {
  10354. agregator.results[index] = value;
  10355. agregator.count++;
  10356. if (agregator.count === agregator.target) {
  10357. agregator.rootPromise._resolve(agregator.results);
  10358. }
  10359. return null;
  10360. }, function (reason) {
  10361. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10362. agregator.rootPromise._reject(reason);
  10363. }
  10364. });
  10365. };
  10366. InternalPromise.all = function (promises) {
  10367. var newPromise = new InternalPromise();
  10368. var agregator = new FulFillmentAgregator();
  10369. agregator.target = promises.length;
  10370. agregator.rootPromise = newPromise;
  10371. if (promises.length) {
  10372. for (var index = 0; index < promises.length; index++) {
  10373. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10374. }
  10375. }
  10376. else {
  10377. newPromise._resolve([]);
  10378. }
  10379. return newPromise;
  10380. };
  10381. InternalPromise.race = function (promises) {
  10382. var newPromise = new InternalPromise();
  10383. if (promises.length) {
  10384. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10385. var promise = promises_1[_i];
  10386. promise.then(function (value) {
  10387. if (newPromise) {
  10388. newPromise._resolve(value);
  10389. newPromise = null;
  10390. }
  10391. return null;
  10392. }, function (reason) {
  10393. if (newPromise) {
  10394. newPromise._reject(reason);
  10395. newPromise = null;
  10396. }
  10397. });
  10398. }
  10399. }
  10400. return newPromise;
  10401. };
  10402. return InternalPromise;
  10403. }());
  10404. /**
  10405. * Helper class that provides a small promise polyfill
  10406. */
  10407. var PromisePolyfill = /** @class */ (function () {
  10408. function PromisePolyfill() {
  10409. }
  10410. /**
  10411. * Static function used to check if the polyfill is required
  10412. * If this is the case then the function will inject the polyfill to window.Promise
  10413. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10414. */
  10415. PromisePolyfill.Apply = function (force) {
  10416. if (force === void 0) { force = false; }
  10417. if (force || typeof Promise === 'undefined') {
  10418. var root = window;
  10419. root.Promise = InternalPromise;
  10420. }
  10421. };
  10422. return PromisePolyfill;
  10423. }());
  10424. BABYLON.PromisePolyfill = PromisePolyfill;
  10425. })(BABYLON || (BABYLON = {}));
  10426. //# sourceMappingURL=babylon.promise.js.map
  10427. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10428. var BABYLON;
  10429. (function (BABYLON) {
  10430. /**
  10431. * Helper class to push actions to a pool of workers.
  10432. */
  10433. var WorkerPool = /** @class */ (function () {
  10434. /**
  10435. * Constructor
  10436. * @param workers Array of workers to use for actions
  10437. */
  10438. function WorkerPool(workers) {
  10439. this._pendingActions = new Array();
  10440. this._workerInfos = workers.map(function (worker) { return ({
  10441. worker: worker,
  10442. active: false
  10443. }); });
  10444. }
  10445. /**
  10446. * Terminates all workers and clears any pending actions.
  10447. */
  10448. WorkerPool.prototype.dispose = function () {
  10449. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10450. var workerInfo = _a[_i];
  10451. workerInfo.worker.terminate();
  10452. }
  10453. delete this._workerInfos;
  10454. delete this._pendingActions;
  10455. };
  10456. /**
  10457. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10458. * pended until a worker has completed its action.
  10459. * @param action The action to perform. Call onComplete when the action is complete.
  10460. */
  10461. WorkerPool.prototype.push = function (action) {
  10462. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10463. var workerInfo = _a[_i];
  10464. if (!workerInfo.active) {
  10465. this._execute(workerInfo, action);
  10466. return;
  10467. }
  10468. }
  10469. this._pendingActions.push(action);
  10470. };
  10471. WorkerPool.prototype._execute = function (workerInfo, action) {
  10472. var _this = this;
  10473. workerInfo.active = true;
  10474. action(workerInfo.worker, function () {
  10475. workerInfo.active = false;
  10476. var nextAction = _this._pendingActions.shift();
  10477. if (nextAction) {
  10478. _this._execute(workerInfo, nextAction);
  10479. }
  10480. });
  10481. };
  10482. return WorkerPool;
  10483. }());
  10484. BABYLON.WorkerPool = WorkerPool;
  10485. })(BABYLON || (BABYLON = {}));
  10486. //# sourceMappingURL=babylon.workerPool.js.map
  10487. var BABYLON;
  10488. (function (BABYLON) {
  10489. /**
  10490. * @hidden
  10491. **/
  10492. var _AlphaState = /** @class */ (function () {
  10493. /**
  10494. * Initializes the state.
  10495. */
  10496. function _AlphaState() {
  10497. this._isAlphaBlendDirty = false;
  10498. this._isBlendFunctionParametersDirty = false;
  10499. this._isBlendEquationParametersDirty = false;
  10500. this._isBlendConstantsDirty = false;
  10501. this._alphaBlend = false;
  10502. this._blendFunctionParameters = new Array(4);
  10503. this._blendEquationParameters = new Array(2);
  10504. this._blendConstants = new Array(4);
  10505. this.reset();
  10506. }
  10507. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10508. get: function () {
  10509. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10510. },
  10511. enumerable: true,
  10512. configurable: true
  10513. });
  10514. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10515. get: function () {
  10516. return this._alphaBlend;
  10517. },
  10518. set: function (value) {
  10519. if (this._alphaBlend === value) {
  10520. return;
  10521. }
  10522. this._alphaBlend = value;
  10523. this._isAlphaBlendDirty = true;
  10524. },
  10525. enumerable: true,
  10526. configurable: true
  10527. });
  10528. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10529. if (this._blendConstants[0] === r &&
  10530. this._blendConstants[1] === g &&
  10531. this._blendConstants[2] === b &&
  10532. this._blendConstants[3] === a) {
  10533. return;
  10534. }
  10535. this._blendConstants[0] = r;
  10536. this._blendConstants[1] = g;
  10537. this._blendConstants[2] = b;
  10538. this._blendConstants[3] = a;
  10539. this._isBlendConstantsDirty = true;
  10540. };
  10541. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10542. if (this._blendFunctionParameters[0] === value0 &&
  10543. this._blendFunctionParameters[1] === value1 &&
  10544. this._blendFunctionParameters[2] === value2 &&
  10545. this._blendFunctionParameters[3] === value3) {
  10546. return;
  10547. }
  10548. this._blendFunctionParameters[0] = value0;
  10549. this._blendFunctionParameters[1] = value1;
  10550. this._blendFunctionParameters[2] = value2;
  10551. this._blendFunctionParameters[3] = value3;
  10552. this._isBlendFunctionParametersDirty = true;
  10553. };
  10554. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10555. if (this._blendEquationParameters[0] === rgb &&
  10556. this._blendEquationParameters[1] === alpha) {
  10557. return;
  10558. }
  10559. this._blendEquationParameters[0] = rgb;
  10560. this._blendEquationParameters[1] = alpha;
  10561. this._isBlendEquationParametersDirty = true;
  10562. };
  10563. _AlphaState.prototype.reset = function () {
  10564. this._alphaBlend = false;
  10565. this._blendFunctionParameters[0] = null;
  10566. this._blendFunctionParameters[1] = null;
  10567. this._blendFunctionParameters[2] = null;
  10568. this._blendFunctionParameters[3] = null;
  10569. this._blendEquationParameters[0] = null;
  10570. this._blendEquationParameters[1] = null;
  10571. this._blendConstants[0] = null;
  10572. this._blendConstants[1] = null;
  10573. this._blendConstants[2] = null;
  10574. this._blendConstants[3] = null;
  10575. this._isAlphaBlendDirty = true;
  10576. this._isBlendFunctionParametersDirty = false;
  10577. this._isBlendEquationParametersDirty = false;
  10578. this._isBlendConstantsDirty = false;
  10579. };
  10580. _AlphaState.prototype.apply = function (gl) {
  10581. if (!this.isDirty) {
  10582. return;
  10583. }
  10584. // Alpha blend
  10585. if (this._isAlphaBlendDirty) {
  10586. if (this._alphaBlend) {
  10587. gl.enable(gl.BLEND);
  10588. }
  10589. else {
  10590. gl.disable(gl.BLEND);
  10591. }
  10592. this._isAlphaBlendDirty = false;
  10593. }
  10594. // Alpha function
  10595. if (this._isBlendFunctionParametersDirty) {
  10596. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10597. this._isBlendFunctionParametersDirty = false;
  10598. }
  10599. // Alpha equation
  10600. if (this._isBlendEquationParametersDirty) {
  10601. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10602. this._isBlendEquationParametersDirty = false;
  10603. }
  10604. // Constants
  10605. if (this._isBlendConstantsDirty) {
  10606. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10607. this._isBlendConstantsDirty = false;
  10608. }
  10609. };
  10610. return _AlphaState;
  10611. }());
  10612. BABYLON._AlphaState = _AlphaState;
  10613. })(BABYLON || (BABYLON = {}));
  10614. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10615. var BABYLON;
  10616. (function (BABYLON) {
  10617. /**
  10618. * @hidden
  10619. **/
  10620. var _DepthCullingState = /** @class */ (function () {
  10621. /**
  10622. * Initializes the state.
  10623. */
  10624. function _DepthCullingState() {
  10625. this._isDepthTestDirty = false;
  10626. this._isDepthMaskDirty = false;
  10627. this._isDepthFuncDirty = false;
  10628. this._isCullFaceDirty = false;
  10629. this._isCullDirty = false;
  10630. this._isZOffsetDirty = false;
  10631. this._isFrontFaceDirty = false;
  10632. this.reset();
  10633. }
  10634. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10635. get: function () {
  10636. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10637. },
  10638. enumerable: true,
  10639. configurable: true
  10640. });
  10641. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10642. get: function () {
  10643. return this._zOffset;
  10644. },
  10645. set: function (value) {
  10646. if (this._zOffset === value) {
  10647. return;
  10648. }
  10649. this._zOffset = value;
  10650. this._isZOffsetDirty = true;
  10651. },
  10652. enumerable: true,
  10653. configurable: true
  10654. });
  10655. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10656. get: function () {
  10657. return this._cullFace;
  10658. },
  10659. set: function (value) {
  10660. if (this._cullFace === value) {
  10661. return;
  10662. }
  10663. this._cullFace = value;
  10664. this._isCullFaceDirty = true;
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10670. get: function () {
  10671. return this._cull;
  10672. },
  10673. set: function (value) {
  10674. if (this._cull === value) {
  10675. return;
  10676. }
  10677. this._cull = value;
  10678. this._isCullDirty = true;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10684. get: function () {
  10685. return this._depthFunc;
  10686. },
  10687. set: function (value) {
  10688. if (this._depthFunc === value) {
  10689. return;
  10690. }
  10691. this._depthFunc = value;
  10692. this._isDepthFuncDirty = true;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10698. get: function () {
  10699. return this._depthMask;
  10700. },
  10701. set: function (value) {
  10702. if (this._depthMask === value) {
  10703. return;
  10704. }
  10705. this._depthMask = value;
  10706. this._isDepthMaskDirty = true;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10712. get: function () {
  10713. return this._depthTest;
  10714. },
  10715. set: function (value) {
  10716. if (this._depthTest === value) {
  10717. return;
  10718. }
  10719. this._depthTest = value;
  10720. this._isDepthTestDirty = true;
  10721. },
  10722. enumerable: true,
  10723. configurable: true
  10724. });
  10725. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10726. get: function () {
  10727. return this._frontFace;
  10728. },
  10729. set: function (value) {
  10730. if (this._frontFace === value) {
  10731. return;
  10732. }
  10733. this._frontFace = value;
  10734. this._isFrontFaceDirty = true;
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. _DepthCullingState.prototype.reset = function () {
  10740. this._depthMask = true;
  10741. this._depthTest = true;
  10742. this._depthFunc = null;
  10743. this._cullFace = null;
  10744. this._cull = null;
  10745. this._zOffset = 0;
  10746. this._frontFace = null;
  10747. this._isDepthTestDirty = true;
  10748. this._isDepthMaskDirty = true;
  10749. this._isDepthFuncDirty = false;
  10750. this._isCullFaceDirty = false;
  10751. this._isCullDirty = false;
  10752. this._isZOffsetDirty = false;
  10753. this._isFrontFaceDirty = false;
  10754. };
  10755. _DepthCullingState.prototype.apply = function (gl) {
  10756. if (!this.isDirty) {
  10757. return;
  10758. }
  10759. // Cull
  10760. if (this._isCullDirty) {
  10761. if (this.cull) {
  10762. gl.enable(gl.CULL_FACE);
  10763. }
  10764. else {
  10765. gl.disable(gl.CULL_FACE);
  10766. }
  10767. this._isCullDirty = false;
  10768. }
  10769. // Cull face
  10770. if (this._isCullFaceDirty) {
  10771. gl.cullFace(this.cullFace);
  10772. this._isCullFaceDirty = false;
  10773. }
  10774. // Depth mask
  10775. if (this._isDepthMaskDirty) {
  10776. gl.depthMask(this.depthMask);
  10777. this._isDepthMaskDirty = false;
  10778. }
  10779. // Depth test
  10780. if (this._isDepthTestDirty) {
  10781. if (this.depthTest) {
  10782. gl.enable(gl.DEPTH_TEST);
  10783. }
  10784. else {
  10785. gl.disable(gl.DEPTH_TEST);
  10786. }
  10787. this._isDepthTestDirty = false;
  10788. }
  10789. // Depth func
  10790. if (this._isDepthFuncDirty) {
  10791. gl.depthFunc(this.depthFunc);
  10792. this._isDepthFuncDirty = false;
  10793. }
  10794. // zOffset
  10795. if (this._isZOffsetDirty) {
  10796. if (this.zOffset) {
  10797. gl.enable(gl.POLYGON_OFFSET_FILL);
  10798. gl.polygonOffset(this.zOffset, 0);
  10799. }
  10800. else {
  10801. gl.disable(gl.POLYGON_OFFSET_FILL);
  10802. }
  10803. this._isZOffsetDirty = false;
  10804. }
  10805. // Front face
  10806. if (this._isFrontFaceDirty) {
  10807. gl.frontFace(this.frontFace);
  10808. this._isFrontFaceDirty = false;
  10809. }
  10810. };
  10811. return _DepthCullingState;
  10812. }());
  10813. BABYLON._DepthCullingState = _DepthCullingState;
  10814. })(BABYLON || (BABYLON = {}));
  10815. //# sourceMappingURL=babylon.depthCullingState.js.map
  10816. var BABYLON;
  10817. (function (BABYLON) {
  10818. /**
  10819. * @hidden
  10820. **/
  10821. var _StencilState = /** @class */ (function () {
  10822. function _StencilState() {
  10823. this._isStencilTestDirty = false;
  10824. this._isStencilMaskDirty = false;
  10825. this._isStencilFuncDirty = false;
  10826. this._isStencilOpDirty = false;
  10827. this.reset();
  10828. }
  10829. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10830. get: function () {
  10831. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10837. get: function () {
  10838. return this._stencilFunc;
  10839. },
  10840. set: function (value) {
  10841. if (this._stencilFunc === value) {
  10842. return;
  10843. }
  10844. this._stencilFunc = value;
  10845. this._isStencilFuncDirty = true;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10851. get: function () {
  10852. return this._stencilFuncRef;
  10853. },
  10854. set: function (value) {
  10855. if (this._stencilFuncRef === value) {
  10856. return;
  10857. }
  10858. this._stencilFuncRef = value;
  10859. this._isStencilFuncDirty = true;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10865. get: function () {
  10866. return this._stencilFuncMask;
  10867. },
  10868. set: function (value) {
  10869. if (this._stencilFuncMask === value) {
  10870. return;
  10871. }
  10872. this._stencilFuncMask = value;
  10873. this._isStencilFuncDirty = true;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10879. get: function () {
  10880. return this._stencilOpStencilFail;
  10881. },
  10882. set: function (value) {
  10883. if (this._stencilOpStencilFail === value) {
  10884. return;
  10885. }
  10886. this._stencilOpStencilFail = value;
  10887. this._isStencilOpDirty = true;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10893. get: function () {
  10894. return this._stencilOpDepthFail;
  10895. },
  10896. set: function (value) {
  10897. if (this._stencilOpDepthFail === value) {
  10898. return;
  10899. }
  10900. this._stencilOpDepthFail = value;
  10901. this._isStencilOpDirty = true;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10907. get: function () {
  10908. return this._stencilOpStencilDepthPass;
  10909. },
  10910. set: function (value) {
  10911. if (this._stencilOpStencilDepthPass === value) {
  10912. return;
  10913. }
  10914. this._stencilOpStencilDepthPass = value;
  10915. this._isStencilOpDirty = true;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10921. get: function () {
  10922. return this._stencilMask;
  10923. },
  10924. set: function (value) {
  10925. if (this._stencilMask === value) {
  10926. return;
  10927. }
  10928. this._stencilMask = value;
  10929. this._isStencilMaskDirty = true;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10935. get: function () {
  10936. return this._stencilTest;
  10937. },
  10938. set: function (value) {
  10939. if (this._stencilTest === value) {
  10940. return;
  10941. }
  10942. this._stencilTest = value;
  10943. this._isStencilTestDirty = true;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. _StencilState.prototype.reset = function () {
  10949. this._stencilTest = false;
  10950. this._stencilMask = 0xFF;
  10951. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10952. this._stencilFuncRef = 1;
  10953. this._stencilFuncMask = 0xFF;
  10954. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10955. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10956. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10957. this._isStencilTestDirty = true;
  10958. this._isStencilMaskDirty = true;
  10959. this._isStencilFuncDirty = true;
  10960. this._isStencilOpDirty = true;
  10961. };
  10962. _StencilState.prototype.apply = function (gl) {
  10963. if (!this.isDirty) {
  10964. return;
  10965. }
  10966. // Stencil test
  10967. if (this._isStencilTestDirty) {
  10968. if (this.stencilTest) {
  10969. gl.enable(gl.STENCIL_TEST);
  10970. }
  10971. else {
  10972. gl.disable(gl.STENCIL_TEST);
  10973. }
  10974. this._isStencilTestDirty = false;
  10975. }
  10976. // Stencil mask
  10977. if (this._isStencilMaskDirty) {
  10978. gl.stencilMask(this.stencilMask);
  10979. this._isStencilMaskDirty = false;
  10980. }
  10981. // Stencil func
  10982. if (this._isStencilFuncDirty) {
  10983. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10984. this._isStencilFuncDirty = false;
  10985. }
  10986. // Stencil op
  10987. if (this._isStencilOpDirty) {
  10988. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10989. this._isStencilOpDirty = false;
  10990. }
  10991. };
  10992. return _StencilState;
  10993. }());
  10994. BABYLON._StencilState = _StencilState;
  10995. })(BABYLON || (BABYLON = {}));
  10996. //# sourceMappingURL=babylon.stencilState.js.map
  10997. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10998. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10999. s = arguments[i];
  11000. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11001. t[p] = s[p];
  11002. }
  11003. return t;
  11004. };
  11005. var BABYLON;
  11006. (function (BABYLON) {
  11007. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11008. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11009. };
  11010. var compileRawShader = function (gl, source, type) {
  11011. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11012. gl.shaderSource(shader, source);
  11013. gl.compileShader(shader);
  11014. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11015. var log = gl.getShaderInfoLog(shader);
  11016. if (log) {
  11017. throw new Error(log);
  11018. }
  11019. }
  11020. if (!shader) {
  11021. throw new Error("Something went wrong while compile the shader.");
  11022. }
  11023. return shader;
  11024. };
  11025. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11026. var magFilter = gl.NEAREST;
  11027. var minFilter = gl.NEAREST;
  11028. switch (samplingMode) {
  11029. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11030. magFilter = gl.LINEAR;
  11031. if (generateMipMaps) {
  11032. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11033. }
  11034. else {
  11035. minFilter = gl.LINEAR;
  11036. }
  11037. break;
  11038. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11039. magFilter = gl.LINEAR;
  11040. if (generateMipMaps) {
  11041. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11042. }
  11043. else {
  11044. minFilter = gl.LINEAR;
  11045. }
  11046. break;
  11047. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11048. magFilter = gl.NEAREST;
  11049. if (generateMipMaps) {
  11050. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11051. }
  11052. else {
  11053. minFilter = gl.NEAREST;
  11054. }
  11055. break;
  11056. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11057. magFilter = gl.NEAREST;
  11058. if (generateMipMaps) {
  11059. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11060. }
  11061. else {
  11062. minFilter = gl.NEAREST;
  11063. }
  11064. break;
  11065. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11066. magFilter = gl.NEAREST;
  11067. if (generateMipMaps) {
  11068. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11069. }
  11070. else {
  11071. minFilter = gl.LINEAR;
  11072. }
  11073. break;
  11074. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11075. magFilter = gl.NEAREST;
  11076. if (generateMipMaps) {
  11077. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11078. }
  11079. else {
  11080. minFilter = gl.LINEAR;
  11081. }
  11082. break;
  11083. case BABYLON.Texture.NEAREST_LINEAR:
  11084. magFilter = gl.NEAREST;
  11085. minFilter = gl.LINEAR;
  11086. break;
  11087. case BABYLON.Texture.NEAREST_NEAREST:
  11088. magFilter = gl.NEAREST;
  11089. minFilter = gl.NEAREST;
  11090. break;
  11091. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11092. magFilter = gl.LINEAR;
  11093. if (generateMipMaps) {
  11094. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11095. }
  11096. else {
  11097. minFilter = gl.NEAREST;
  11098. }
  11099. break;
  11100. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11101. magFilter = gl.LINEAR;
  11102. if (generateMipMaps) {
  11103. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11104. }
  11105. else {
  11106. minFilter = gl.NEAREST;
  11107. }
  11108. break;
  11109. case BABYLON.Texture.LINEAR_LINEAR:
  11110. magFilter = gl.LINEAR;
  11111. minFilter = gl.LINEAR;
  11112. break;
  11113. case BABYLON.Texture.LINEAR_NEAREST:
  11114. magFilter = gl.LINEAR;
  11115. minFilter = gl.NEAREST;
  11116. break;
  11117. }
  11118. return {
  11119. min: minFilter,
  11120. mag: magFilter
  11121. };
  11122. };
  11123. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11124. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11125. var img;
  11126. var onload = function () {
  11127. loadedImages[index] = img;
  11128. loadedImages._internalCount++;
  11129. if (scene) {
  11130. scene._removePendingData(img);
  11131. }
  11132. if (loadedImages._internalCount === 6) {
  11133. onfinish(loadedImages);
  11134. }
  11135. };
  11136. var onerror = function (message, exception) {
  11137. if (scene) {
  11138. scene._removePendingData(img);
  11139. }
  11140. if (onErrorCallBack) {
  11141. onErrorCallBack(message, exception);
  11142. }
  11143. };
  11144. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11145. if (scene) {
  11146. scene._addPendingData(img);
  11147. }
  11148. };
  11149. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11150. if (onError === void 0) { onError = null; }
  11151. var loadedImages = [];
  11152. loadedImages._internalCount = 0;
  11153. for (var index = 0; index < 6; index++) {
  11154. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11155. }
  11156. };
  11157. var BufferPointer = /** @class */ (function () {
  11158. function BufferPointer() {
  11159. }
  11160. return BufferPointer;
  11161. }());
  11162. /**
  11163. * Interface for attribute information associated with buffer instanciation
  11164. */
  11165. var InstancingAttributeInfo = /** @class */ (function () {
  11166. function InstancingAttributeInfo() {
  11167. }
  11168. return InstancingAttributeInfo;
  11169. }());
  11170. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11171. /**
  11172. * Define options used to create a render target texture
  11173. */
  11174. var RenderTargetCreationOptions = /** @class */ (function () {
  11175. function RenderTargetCreationOptions() {
  11176. }
  11177. return RenderTargetCreationOptions;
  11178. }());
  11179. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11180. /**
  11181. * Define options used to create a depth texture
  11182. */
  11183. var DepthTextureCreationOptions = /** @class */ (function () {
  11184. function DepthTextureCreationOptions() {
  11185. }
  11186. return DepthTextureCreationOptions;
  11187. }());
  11188. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11189. /**
  11190. * Class used to describe the capabilities of the engine relatively to the current browser
  11191. */
  11192. var EngineCapabilities = /** @class */ (function () {
  11193. function EngineCapabilities() {
  11194. }
  11195. return EngineCapabilities;
  11196. }());
  11197. BABYLON.EngineCapabilities = EngineCapabilities;
  11198. /**
  11199. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11200. */
  11201. var Engine = /** @class */ (function () {
  11202. /**
  11203. * Creates a new engine
  11204. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11205. * @param antialias defines enable antialiasing (default: false)
  11206. * @param options defines further options to be sent to the getContext() function
  11207. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11208. */
  11209. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11210. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11211. var _this = this;
  11212. // Public members
  11213. /**
  11214. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11215. */
  11216. this.forcePOTTextures = false;
  11217. /**
  11218. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11219. */
  11220. this.isFullscreen = false;
  11221. /**
  11222. * Gets a boolean indicating if the pointer is currently locked
  11223. */
  11224. this.isPointerLock = false;
  11225. /**
  11226. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11227. */
  11228. this.cullBackFaces = true;
  11229. /**
  11230. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11231. */
  11232. this.renderEvenInBackground = true;
  11233. /**
  11234. * Gets or sets a boolean indicating that cache can be kept between frames
  11235. */
  11236. this.preventCacheWipeBetweenFrames = false;
  11237. /**
  11238. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11239. **/
  11240. this.enableOfflineSupport = false;
  11241. /**
  11242. * 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)
  11243. **/
  11244. this.disableManifestCheck = false;
  11245. /**
  11246. * Gets the list of created scenes
  11247. */
  11248. this.scenes = new Array();
  11249. /**
  11250. * Gets the list of created postprocesses
  11251. */
  11252. this.postProcesses = new Array();
  11253. // Observables
  11254. /**
  11255. * Observable event triggered each time the rendering canvas is resized
  11256. */
  11257. this.onResizeObservable = new BABYLON.Observable();
  11258. /**
  11259. * Observable event triggered each time the canvas loses focus
  11260. */
  11261. this.onCanvasBlurObservable = new BABYLON.Observable();
  11262. /**
  11263. * Observable event triggered each time the canvas gains focus
  11264. */
  11265. this.onCanvasFocusObservable = new BABYLON.Observable();
  11266. /**
  11267. * Observable event triggered each time the canvas receives pointerout event
  11268. */
  11269. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11270. /**
  11271. * Observable event triggered before each texture is initialized
  11272. */
  11273. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11274. //WebVR
  11275. this._vrDisplay = undefined;
  11276. this._vrSupported = false;
  11277. this._vrExclusivePointerMode = false;
  11278. // Uniform buffers list
  11279. /**
  11280. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11281. */
  11282. this.disableUniformBuffers = false;
  11283. /** @hidden */
  11284. this._uniformBuffers = new Array();
  11285. // Observables
  11286. /**
  11287. * Observable raised when the engine begins a new frame
  11288. */
  11289. this.onBeginFrameObservable = new BABYLON.Observable();
  11290. /**
  11291. * Observable raised when the engine ends the current frame
  11292. */
  11293. this.onEndFrameObservable = new BABYLON.Observable();
  11294. /**
  11295. * Observable raised when the engine is about to compile a shader
  11296. */
  11297. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11298. /**
  11299. * Observable raised when the engine has jsut compiled a shader
  11300. */
  11301. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11302. this._windowIsBackground = false;
  11303. this._webGLVersion = 1.0;
  11304. /** @hidden */
  11305. this._badOS = false;
  11306. /** @hidden */
  11307. this._badDesktopOS = false;
  11308. /**
  11309. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11310. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11311. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11312. */
  11313. this.disableTextureBindingOptimization = false;
  11314. /**
  11315. * Observable signaled when VR display mode changes
  11316. */
  11317. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11318. /**
  11319. * Observable signaled when VR request present is complete
  11320. */
  11321. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11322. /**
  11323. * Observable signaled when VR request present starts
  11324. */
  11325. this.onVRRequestPresentStart = new BABYLON.Observable();
  11326. this._colorWrite = true;
  11327. /** @hidden */
  11328. this._drawCalls = new BABYLON.PerfCounter();
  11329. /** @hidden */
  11330. this._textureCollisions = new BABYLON.PerfCounter();
  11331. this._renderingQueueLaunched = false;
  11332. this._activeRenderLoops = new Array();
  11333. // Deterministic lockstepMaxSteps
  11334. this._deterministicLockstep = false;
  11335. this._lockstepMaxSteps = 4;
  11336. // Lost context
  11337. /**
  11338. * Observable signaled when a context lost event is raised
  11339. */
  11340. this.onContextLostObservable = new BABYLON.Observable();
  11341. /**
  11342. * Observable signaled when a context restored event is raised
  11343. */
  11344. this.onContextRestoredObservable = new BABYLON.Observable();
  11345. this._contextWasLost = false;
  11346. this._doNotHandleContextLost = false;
  11347. // FPS
  11348. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11349. this._fps = 60;
  11350. this._deltaTime = 0;
  11351. /**
  11352. * Turn this value on if you want to pause FPS computation when in background
  11353. */
  11354. this.disablePerformanceMonitorInBackground = false;
  11355. // States
  11356. /** @hidden */
  11357. this._depthCullingState = new BABYLON._DepthCullingState();
  11358. /** @hidden */
  11359. this._stencilState = new BABYLON._StencilState();
  11360. /** @hidden */
  11361. this._alphaState = new BABYLON._AlphaState();
  11362. /** @hidden */
  11363. this._alphaMode = Engine.ALPHA_DISABLE;
  11364. // Cache
  11365. this._internalTexturesCache = new Array();
  11366. /** @hidden */
  11367. this._activeChannel = 0;
  11368. this._currentTextureChannel = -1;
  11369. /** @hidden */
  11370. this._boundTexturesCache = {};
  11371. this._compiledEffects = {};
  11372. this._vertexAttribArraysEnabled = [];
  11373. this._uintIndicesCurrentlySet = false;
  11374. this._currentBoundBuffer = new Array();
  11375. this._currentBufferPointers = new Array();
  11376. this._currentInstanceLocations = new Array();
  11377. this._currentInstanceBuffers = new Array();
  11378. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11379. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11380. this._vaoRecordInProgress = false;
  11381. this._mustWipeVertexAttributes = false;
  11382. this._nextFreeTextureSlots = new Array();
  11383. this._maxSimultaneousTextures = 0;
  11384. this._activeRequests = new Array();
  11385. // Hardware supported Compressed Textures
  11386. this._texturesSupported = new Array();
  11387. /**
  11388. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11389. */
  11390. this.premultipliedAlpha = true;
  11391. this._onVRFullScreenTriggered = function () {
  11392. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11393. //get the old size before we change
  11394. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11395. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11396. //get the width and height, change the render size
  11397. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11398. _this.setHardwareScalingLevel(1);
  11399. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11400. }
  11401. else {
  11402. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11403. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11404. }
  11405. };
  11406. this._boundUniforms = {};
  11407. // Register promises
  11408. BABYLON.PromisePolyfill.Apply();
  11409. var canvas = null;
  11410. Engine.Instances.push(this);
  11411. if (!canvasOrContext) {
  11412. return;
  11413. }
  11414. options = options || {};
  11415. if (canvasOrContext.getContext) {
  11416. canvas = canvasOrContext;
  11417. this._renderingCanvas = canvas;
  11418. if (antialias != null) {
  11419. options.antialias = antialias;
  11420. }
  11421. if (options.deterministicLockstep === undefined) {
  11422. options.deterministicLockstep = false;
  11423. }
  11424. if (options.lockstepMaxSteps === undefined) {
  11425. options.lockstepMaxSteps = 4;
  11426. }
  11427. if (options.preserveDrawingBuffer === undefined) {
  11428. options.preserveDrawingBuffer = false;
  11429. }
  11430. if (options.audioEngine === undefined) {
  11431. options.audioEngine = true;
  11432. }
  11433. if (options.stencil === undefined) {
  11434. options.stencil = true;
  11435. }
  11436. if (options.premultipliedAlpha === false) {
  11437. this.premultipliedAlpha = false;
  11438. }
  11439. this._deterministicLockstep = options.deterministicLockstep;
  11440. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11441. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11442. // Exceptions
  11443. if (navigator && navigator.userAgent) {
  11444. var ua = navigator.userAgent;
  11445. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11446. var exception = _a[_i];
  11447. var key = exception.key;
  11448. var targets = exception.targets;
  11449. if (ua.indexOf(key) > -1) {
  11450. if (exception.capture && exception.captureConstraint) {
  11451. var capture = exception.capture;
  11452. var constraint = exception.captureConstraint;
  11453. var regex = new RegExp(capture);
  11454. var matches = regex.exec(ua);
  11455. if (matches && matches.length > 0) {
  11456. var capturedValue = parseInt(matches[matches.length - 1]);
  11457. if (capturedValue >= constraint) {
  11458. continue;
  11459. }
  11460. }
  11461. }
  11462. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11463. var target = targets_1[_b];
  11464. switch (target) {
  11465. case "uniformBuffer":
  11466. this.disableUniformBuffers = true;
  11467. break;
  11468. case "textureBindingOptimization":
  11469. this.disableTextureBindingOptimization = true;
  11470. break;
  11471. }
  11472. }
  11473. }
  11474. }
  11475. }
  11476. // GL
  11477. if (!options.disableWebGL2Support) {
  11478. try {
  11479. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11480. if (this._gl) {
  11481. this._webGLVersion = 2.0;
  11482. }
  11483. }
  11484. catch (e) {
  11485. // Do nothing
  11486. }
  11487. }
  11488. if (!this._gl) {
  11489. if (!canvas) {
  11490. throw new Error("The provided canvas is null or undefined.");
  11491. }
  11492. try {
  11493. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11494. }
  11495. catch (e) {
  11496. throw new Error("WebGL not supported");
  11497. }
  11498. }
  11499. if (!this._gl) {
  11500. throw new Error("WebGL not supported");
  11501. }
  11502. this._onCanvasFocus = function () {
  11503. _this.onCanvasFocusObservable.notifyObservers(_this);
  11504. };
  11505. this._onCanvasBlur = function () {
  11506. _this.onCanvasBlurObservable.notifyObservers(_this);
  11507. };
  11508. canvas.addEventListener("focus", this._onCanvasFocus);
  11509. canvas.addEventListener("blur", this._onCanvasBlur);
  11510. this._onBlur = function () {
  11511. if (_this.disablePerformanceMonitorInBackground) {
  11512. _this._performanceMonitor.disable();
  11513. }
  11514. _this._windowIsBackground = true;
  11515. };
  11516. this._onFocus = function () {
  11517. if (_this.disablePerformanceMonitorInBackground) {
  11518. _this._performanceMonitor.enable();
  11519. }
  11520. _this._windowIsBackground = false;
  11521. };
  11522. this._onCanvasPointerOut = function (ev) {
  11523. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11524. };
  11525. window.addEventListener("blur", this._onBlur);
  11526. window.addEventListener("focus", this._onFocus);
  11527. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11528. // Context lost
  11529. if (!this._doNotHandleContextLost) {
  11530. this._onContextLost = function (evt) {
  11531. evt.preventDefault();
  11532. _this._contextWasLost = true;
  11533. BABYLON.Tools.Warn("WebGL context lost.");
  11534. _this.onContextLostObservable.notifyObservers(_this);
  11535. };
  11536. this._onContextRestored = function (evt) {
  11537. // Adding a timeout to avoid race condition at browser level
  11538. setTimeout(function () {
  11539. // Rebuild gl context
  11540. _this._initGLContext();
  11541. // Rebuild effects
  11542. _this._rebuildEffects();
  11543. // Rebuild textures
  11544. _this._rebuildInternalTextures();
  11545. // Rebuild buffers
  11546. _this._rebuildBuffers();
  11547. // Cache
  11548. _this.wipeCaches(true);
  11549. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11550. _this.onContextRestoredObservable.notifyObservers(_this);
  11551. _this._contextWasLost = false;
  11552. }, 0);
  11553. };
  11554. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11555. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11556. }
  11557. }
  11558. else {
  11559. this._gl = canvasOrContext;
  11560. this._renderingCanvas = this._gl.canvas;
  11561. if (this._gl.renderbufferStorageMultisample) {
  11562. this._webGLVersion = 2.0;
  11563. }
  11564. options.stencil = this._gl.getContextAttributes().stencil;
  11565. }
  11566. // Viewport
  11567. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11568. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11569. this.resize();
  11570. this._isStencilEnable = options.stencil ? true : false;
  11571. this._initGLContext();
  11572. if (canvas) {
  11573. // Fullscreen
  11574. this._onFullscreenChange = function () {
  11575. if (document.fullscreen !== undefined) {
  11576. _this.isFullscreen = document.fullscreen;
  11577. }
  11578. else if (document.mozFullScreen !== undefined) {
  11579. _this.isFullscreen = document.mozFullScreen;
  11580. }
  11581. else if (document.webkitIsFullScreen !== undefined) {
  11582. _this.isFullscreen = document.webkitIsFullScreen;
  11583. }
  11584. else if (document.msIsFullScreen !== undefined) {
  11585. _this.isFullscreen = document.msIsFullScreen;
  11586. }
  11587. // Pointer lock
  11588. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11589. canvas.requestPointerLock = canvas.requestPointerLock ||
  11590. canvas.msRequestPointerLock ||
  11591. canvas.mozRequestPointerLock ||
  11592. canvas.webkitRequestPointerLock;
  11593. if (canvas.requestPointerLock) {
  11594. canvas.requestPointerLock();
  11595. }
  11596. }
  11597. };
  11598. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11599. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11600. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11601. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11602. // Pointer lock
  11603. this._onPointerLockChange = function () {
  11604. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11605. document.webkitPointerLockElement === canvas ||
  11606. document.msPointerLockElement === canvas ||
  11607. document.pointerLockElement === canvas);
  11608. };
  11609. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11610. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11611. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11612. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11613. this._onVRDisplayPointerRestricted = function () {
  11614. if (canvas) {
  11615. canvas.requestPointerLock();
  11616. }
  11617. };
  11618. this._onVRDisplayPointerUnrestricted = function () {
  11619. document.exitPointerLock();
  11620. };
  11621. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11622. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11623. }
  11624. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11625. Engine.audioEngine = new BABYLON.AudioEngine();
  11626. }
  11627. // Prepare buffer pointers
  11628. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11629. this._currentBufferPointers[i] = new BufferPointer();
  11630. }
  11631. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11632. // Load WebVR Devices
  11633. if (options.autoEnableWebVR) {
  11634. this.initWebVR();
  11635. }
  11636. // Detect if we are running on a faulty buggy OS.
  11637. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11638. // Detect if we are running on a faulty buggy desktop OS.
  11639. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11640. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11641. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11642. }
  11643. Object.defineProperty(Engine, "LastCreatedEngine", {
  11644. /**
  11645. * Gets the latest created engine
  11646. */
  11647. get: function () {
  11648. if (Engine.Instances.length === 0) {
  11649. return null;
  11650. }
  11651. return Engine.Instances[Engine.Instances.length - 1];
  11652. },
  11653. enumerable: true,
  11654. configurable: true
  11655. });
  11656. Object.defineProperty(Engine, "LastCreatedScene", {
  11657. /**
  11658. * Gets the latest created scene
  11659. */
  11660. get: function () {
  11661. var lastCreatedEngine = Engine.LastCreatedEngine;
  11662. if (!lastCreatedEngine) {
  11663. return null;
  11664. }
  11665. if (lastCreatedEngine.scenes.length === 0) {
  11666. return null;
  11667. }
  11668. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. /**
  11674. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11675. * @param flag defines which part of the materials must be marked as dirty
  11676. * @param predicate defines a predicate used to filter which materials should be affected
  11677. */
  11678. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11679. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11680. var engine = Engine.Instances[engineIndex];
  11681. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11682. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11683. }
  11684. }
  11685. };
  11686. Object.defineProperty(Engine, "NEVER", {
  11687. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11688. get: function () {
  11689. return Engine._NEVER;
  11690. },
  11691. enumerable: true,
  11692. configurable: true
  11693. });
  11694. Object.defineProperty(Engine, "ALWAYS", {
  11695. /** 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 */
  11696. get: function () {
  11697. return Engine._ALWAYS;
  11698. },
  11699. enumerable: true,
  11700. configurable: true
  11701. });
  11702. Object.defineProperty(Engine, "LESS", {
  11703. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11704. get: function () {
  11705. return Engine._LESS;
  11706. },
  11707. enumerable: true,
  11708. configurable: true
  11709. });
  11710. Object.defineProperty(Engine, "EQUAL", {
  11711. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11712. get: function () {
  11713. return Engine._EQUAL;
  11714. },
  11715. enumerable: true,
  11716. configurable: true
  11717. });
  11718. Object.defineProperty(Engine, "LEQUAL", {
  11719. /** 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 */
  11720. get: function () {
  11721. return Engine._LEQUAL;
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Engine, "GREATER", {
  11727. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11728. get: function () {
  11729. return Engine._GREATER;
  11730. },
  11731. enumerable: true,
  11732. configurable: true
  11733. });
  11734. Object.defineProperty(Engine, "GEQUAL", {
  11735. /** 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 */
  11736. get: function () {
  11737. return Engine._GEQUAL;
  11738. },
  11739. enumerable: true,
  11740. configurable: true
  11741. });
  11742. Object.defineProperty(Engine, "NOTEQUAL", {
  11743. /** 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 */
  11744. get: function () {
  11745. return Engine._NOTEQUAL;
  11746. },
  11747. enumerable: true,
  11748. configurable: true
  11749. });
  11750. Object.defineProperty(Engine, "KEEP", {
  11751. /** Passed to stencilOperation to specify that stencil value must be kept */
  11752. get: function () {
  11753. return Engine._KEEP;
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. Object.defineProperty(Engine, "REPLACE", {
  11759. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11760. get: function () {
  11761. return Engine._REPLACE;
  11762. },
  11763. enumerable: true,
  11764. configurable: true
  11765. });
  11766. Object.defineProperty(Engine, "INCR", {
  11767. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11768. get: function () {
  11769. return Engine._INCR;
  11770. },
  11771. enumerable: true,
  11772. configurable: true
  11773. });
  11774. Object.defineProperty(Engine, "DECR", {
  11775. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11776. get: function () {
  11777. return Engine._DECR;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Object.defineProperty(Engine, "INVERT", {
  11783. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11784. get: function () {
  11785. return Engine._INVERT;
  11786. },
  11787. enumerable: true,
  11788. configurable: true
  11789. });
  11790. Object.defineProperty(Engine, "INCR_WRAP", {
  11791. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11792. get: function () {
  11793. return Engine._INCR_WRAP;
  11794. },
  11795. enumerable: true,
  11796. configurable: true
  11797. });
  11798. Object.defineProperty(Engine, "DECR_WRAP", {
  11799. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11800. get: function () {
  11801. return Engine._DECR_WRAP;
  11802. },
  11803. enumerable: true,
  11804. configurable: true
  11805. });
  11806. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11807. // Alpha
  11808. /** Defines that alpha blending is disabled */
  11809. get: function () {
  11810. return Engine._ALPHA_DISABLE;
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11816. /** Defines that alpha blending to SRC + DEST */
  11817. get: function () {
  11818. return Engine._ALPHA_ONEONE;
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. Object.defineProperty(Engine, "ALPHA_ADD", {
  11824. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11825. get: function () {
  11826. return Engine._ALPHA_ADD;
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11832. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11833. get: function () {
  11834. return Engine._ALPHA_COMBINE;
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11840. /** Defines that alpha blending to DEST - SRC * DEST */
  11841. get: function () {
  11842. return Engine._ALPHA_SUBTRACT;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11848. /** Defines that alpha blending to SRC * DEST */
  11849. get: function () {
  11850. return Engine._ALPHA_MULTIPLY;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11856. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11857. get: function () {
  11858. return Engine._ALPHA_MAXIMIZED;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11864. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11865. get: function () {
  11866. return Engine._ALPHA_PREMULTIPLIED;
  11867. },
  11868. enumerable: true,
  11869. configurable: true
  11870. });
  11871. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11872. /**
  11873. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11874. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11875. */
  11876. get: function () {
  11877. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11883. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11884. get: function () {
  11885. return Engine._ALPHA_INTERPOLATE;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11891. /**
  11892. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11893. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11894. */
  11895. get: function () {
  11896. return Engine._ALPHA_SCREENMODE;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11902. // Delays
  11903. /** Defines that the ressource is not delayed*/
  11904. get: function () {
  11905. return Engine._DELAYLOADSTATE_NONE;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11911. /** Defines that the ressource was successfully delay loaded */
  11912. get: function () {
  11913. return Engine._DELAYLOADSTATE_LOADED;
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11919. /** Defines that the ressource is currently delay loading */
  11920. get: function () {
  11921. return Engine._DELAYLOADSTATE_LOADING;
  11922. },
  11923. enumerable: true,
  11924. configurable: true
  11925. });
  11926. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11927. /** Defines that the ressource is delayed and has not started loading */
  11928. get: function () {
  11929. return Engine._DELAYLOADSTATE_NOTLOADED;
  11930. },
  11931. enumerable: true,
  11932. configurable: true
  11933. });
  11934. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11935. /** ALPHA */
  11936. get: function () {
  11937. return Engine._TEXTUREFORMAT_ALPHA;
  11938. },
  11939. enumerable: true,
  11940. configurable: true
  11941. });
  11942. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11943. /** LUMINANCE */
  11944. get: function () {
  11945. return Engine._TEXTUREFORMAT_LUMINANCE;
  11946. },
  11947. enumerable: true,
  11948. configurable: true
  11949. });
  11950. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11951. /**
  11952. * R
  11953. */
  11954. get: function () {
  11955. return Engine._TEXTUREFORMAT_R;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11961. /**
  11962. * RG
  11963. */
  11964. get: function () {
  11965. return Engine._TEXTUREFORMAT_RG;
  11966. },
  11967. enumerable: true,
  11968. configurable: true
  11969. });
  11970. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11971. /** LUMINANCE_ALPHA */
  11972. get: function () {
  11973. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11979. /** RGB */
  11980. get: function () {
  11981. return Engine._TEXTUREFORMAT_RGB;
  11982. },
  11983. enumerable: true,
  11984. configurable: true
  11985. });
  11986. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11987. /** RGBA */
  11988. get: function () {
  11989. return Engine._TEXTUREFORMAT_RGBA;
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11995. /** UNSIGNED_INT */
  11996. get: function () {
  11997. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12003. /** FLOAT */
  12004. get: function () {
  12005. return Engine._TEXTURETYPE_FLOAT;
  12006. },
  12007. enumerable: true,
  12008. configurable: true
  12009. });
  12010. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12011. /** HALF_FLOAT */
  12012. get: function () {
  12013. return Engine._TEXTURETYPE_HALF_FLOAT;
  12014. },
  12015. enumerable: true,
  12016. configurable: true
  12017. });
  12018. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12019. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12020. get: function () {
  12021. return Engine._SCALEMODE_FLOOR;
  12022. },
  12023. enumerable: true,
  12024. configurable: true
  12025. });
  12026. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12027. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12028. get: function () {
  12029. return Engine._SCALEMODE_NEAREST;
  12030. },
  12031. enumerable: true,
  12032. configurable: true
  12033. });
  12034. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12035. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12036. get: function () {
  12037. return Engine._SCALEMODE_CEILING;
  12038. },
  12039. enumerable: true,
  12040. configurable: true
  12041. });
  12042. Object.defineProperty(Engine, "Version", {
  12043. /**
  12044. * Returns the current version of the framework
  12045. */
  12046. get: function () {
  12047. return "3.3.0-alpha.6";
  12048. },
  12049. enumerable: true,
  12050. configurable: true
  12051. });
  12052. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12053. /**
  12054. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12055. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12056. */
  12057. get: function () {
  12058. return this._vrExclusivePointerMode;
  12059. },
  12060. enumerable: true,
  12061. configurable: true
  12062. });
  12063. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12064. /**
  12065. * Gets a boolean indicating that the engine supports uniform buffers
  12066. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12067. */
  12068. get: function () {
  12069. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12070. },
  12071. enumerable: true,
  12072. configurable: true
  12073. });
  12074. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12075. /**
  12076. * Gets a boolean indicating that only power of 2 textures are supported
  12077. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12078. */
  12079. get: function () {
  12080. return this._webGLVersion < 2 || this.forcePOTTextures;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12086. /**
  12087. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12088. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12089. */
  12090. get: function () {
  12091. return this._doNotHandleContextLost;
  12092. },
  12093. set: function (value) {
  12094. this._doNotHandleContextLost = value;
  12095. },
  12096. enumerable: true,
  12097. configurable: true
  12098. });
  12099. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12100. /**
  12101. * Gets the performance monitor attached to this engine
  12102. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12103. */
  12104. get: function () {
  12105. return this._performanceMonitor;
  12106. },
  12107. enumerable: true,
  12108. configurable: true
  12109. });
  12110. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12111. /**
  12112. * Gets the list of texture formats supported
  12113. */
  12114. get: function () {
  12115. return this._texturesSupported;
  12116. },
  12117. enumerable: true,
  12118. configurable: true
  12119. });
  12120. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12121. /**
  12122. * Gets the list of texture formats in use
  12123. */
  12124. get: function () {
  12125. return this._textureFormatInUse;
  12126. },
  12127. enumerable: true,
  12128. configurable: true
  12129. });
  12130. Object.defineProperty(Engine.prototype, "currentViewport", {
  12131. /**
  12132. * Gets the current viewport
  12133. */
  12134. get: function () {
  12135. return this._cachedViewport;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12141. /**
  12142. * Gets the default empty texture
  12143. */
  12144. get: function () {
  12145. if (!this._emptyTexture) {
  12146. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12147. }
  12148. return this._emptyTexture;
  12149. },
  12150. enumerable: true,
  12151. configurable: true
  12152. });
  12153. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12154. /**
  12155. * Gets the default empty 3D texture
  12156. */
  12157. get: function () {
  12158. if (!this._emptyTexture3D) {
  12159. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12160. }
  12161. return this._emptyTexture3D;
  12162. },
  12163. enumerable: true,
  12164. configurable: true
  12165. });
  12166. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12167. /**
  12168. * Gets the default empty cube texture
  12169. */
  12170. get: function () {
  12171. if (!this._emptyCubeTexture) {
  12172. var faceData = new Uint8Array(4);
  12173. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12174. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12175. }
  12176. return this._emptyCubeTexture;
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. Engine.prototype._rebuildInternalTextures = function () {
  12182. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12183. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12184. var internalTexture = currentState_1[_i];
  12185. internalTexture._rebuild();
  12186. }
  12187. };
  12188. Engine.prototype._rebuildEffects = function () {
  12189. for (var key in this._compiledEffects) {
  12190. var effect = this._compiledEffects[key];
  12191. effect._prepareEffect();
  12192. }
  12193. BABYLON.Effect.ResetCache();
  12194. };
  12195. Engine.prototype._rebuildBuffers = function () {
  12196. // Index / Vertex
  12197. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12198. var scene = _a[_i];
  12199. scene.resetCachedMaterial();
  12200. scene._rebuildGeometries();
  12201. scene._rebuildTextures();
  12202. }
  12203. // Uniforms
  12204. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12205. var uniformBuffer = _c[_b];
  12206. uniformBuffer._rebuild();
  12207. }
  12208. };
  12209. Engine.prototype._initGLContext = function () {
  12210. // Caps
  12211. this._caps = new EngineCapabilities();
  12212. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12213. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12214. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12215. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12216. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12217. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12218. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12219. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12220. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12221. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12222. // Infos
  12223. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12224. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12225. if (rendererInfo != null) {
  12226. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12227. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12228. }
  12229. if (!this._glVendor) {
  12230. this._glVendor = "Unknown vendor";
  12231. }
  12232. if (!this._glRenderer) {
  12233. this._glRenderer = "Unknown renderer";
  12234. }
  12235. // Constants
  12236. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12237. if (this._gl.RGBA16F !== 0x881A) {
  12238. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12239. }
  12240. if (this._gl.RGBA32F !== 0x8814) {
  12241. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12242. }
  12243. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12244. this._gl.DEPTH24_STENCIL8 = 35056;
  12245. }
  12246. // Extensions
  12247. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12248. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12249. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12250. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12251. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12252. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12253. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12254. 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');
  12255. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12256. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12257. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12258. this._caps.highPrecisionShaderSupported = true;
  12259. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12260. if (this._caps.timerQuery) {
  12261. if (this._webGLVersion === 1) {
  12262. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12263. }
  12264. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12265. }
  12266. // Checks if some of the format renders first to allow the use of webgl inspector.
  12267. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12268. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12269. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12270. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12271. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12272. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12273. if (this._webGLVersion > 1) {
  12274. this._gl.HALF_FLOAT_OES = 0x140B;
  12275. }
  12276. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12277. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12278. // Draw buffers
  12279. if (this._webGLVersion > 1) {
  12280. this._caps.drawBuffersExtension = true;
  12281. }
  12282. else {
  12283. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12284. if (drawBuffersExtension !== null) {
  12285. this._caps.drawBuffersExtension = true;
  12286. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12287. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12288. for (var i = 0; i < 16; i++) {
  12289. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12290. }
  12291. }
  12292. else {
  12293. this._caps.drawBuffersExtension = false;
  12294. }
  12295. }
  12296. // Depth Texture
  12297. if (this._webGLVersion > 1) {
  12298. this._caps.depthTextureExtension = true;
  12299. }
  12300. else {
  12301. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12302. if (depthTextureExtension != null) {
  12303. this._caps.depthTextureExtension = true;
  12304. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12305. }
  12306. }
  12307. // Vertex array object
  12308. if (this._webGLVersion > 1) {
  12309. this._caps.vertexArrayObject = true;
  12310. }
  12311. else {
  12312. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12313. if (vertexArrayObjectExtension != null) {
  12314. this._caps.vertexArrayObject = true;
  12315. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12316. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12317. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12318. }
  12319. else {
  12320. this._caps.vertexArrayObject = false;
  12321. }
  12322. }
  12323. // Instances count
  12324. if (this._webGLVersion > 1) {
  12325. this._caps.instancedArrays = true;
  12326. }
  12327. else {
  12328. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12329. if (instanceExtension != null) {
  12330. this._caps.instancedArrays = true;
  12331. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12332. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12333. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12334. }
  12335. else {
  12336. this._caps.instancedArrays = false;
  12337. }
  12338. }
  12339. // Intelligently add supported compressed formats in order to check for.
  12340. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12341. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12342. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12343. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12344. if (this._caps.astc)
  12345. this.texturesSupported.push('-astc.ktx');
  12346. if (this._caps.s3tc)
  12347. this.texturesSupported.push('-dxt.ktx');
  12348. if (this._caps.pvrtc)
  12349. this.texturesSupported.push('-pvrtc.ktx');
  12350. if (this._caps.etc2)
  12351. this.texturesSupported.push('-etc2.ktx');
  12352. if (this._caps.etc1)
  12353. this.texturesSupported.push('-etc1.ktx');
  12354. if (this._gl.getShaderPrecisionFormat) {
  12355. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12356. if (highp) {
  12357. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12358. }
  12359. }
  12360. // Depth buffer
  12361. this.setDepthBuffer(true);
  12362. this.setDepthFunctionToLessOrEqual();
  12363. this.setDepthWrite(true);
  12364. // Texture maps
  12365. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12366. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12367. this._nextFreeTextureSlots.push(slot);
  12368. }
  12369. };
  12370. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12371. /**
  12372. * Gets version of the current webGL context
  12373. */
  12374. get: function () {
  12375. return this._webGLVersion;
  12376. },
  12377. enumerable: true,
  12378. configurable: true
  12379. });
  12380. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12381. /**
  12382. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12383. */
  12384. get: function () {
  12385. return this._isStencilEnable;
  12386. },
  12387. enumerable: true,
  12388. configurable: true
  12389. });
  12390. Engine.prototype._prepareWorkingCanvas = function () {
  12391. if (this._workingCanvas) {
  12392. return;
  12393. }
  12394. this._workingCanvas = document.createElement("canvas");
  12395. var context = this._workingCanvas.getContext("2d");
  12396. if (context) {
  12397. this._workingContext = context;
  12398. }
  12399. };
  12400. /**
  12401. * Reset the texture cache to empty state
  12402. */
  12403. Engine.prototype.resetTextureCache = function () {
  12404. for (var key in this._boundTexturesCache) {
  12405. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12406. continue;
  12407. }
  12408. var boundTexture = this._boundTexturesCache[key];
  12409. if (boundTexture) {
  12410. this._removeDesignatedSlot(boundTexture);
  12411. }
  12412. this._boundTexturesCache[key] = null;
  12413. }
  12414. if (!this.disableTextureBindingOptimization) {
  12415. this._nextFreeTextureSlots = [];
  12416. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12417. this._nextFreeTextureSlots.push(slot);
  12418. }
  12419. }
  12420. this._currentTextureChannel = -1;
  12421. };
  12422. /**
  12423. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12424. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12425. * @returns true if engine is in deterministic lock step mode
  12426. */
  12427. Engine.prototype.isDeterministicLockStep = function () {
  12428. return this._deterministicLockstep;
  12429. };
  12430. /**
  12431. * Gets the max steps when engine is running in deterministic lock step
  12432. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12433. * @returns the max steps
  12434. */
  12435. Engine.prototype.getLockstepMaxSteps = function () {
  12436. return this._lockstepMaxSteps;
  12437. };
  12438. /**
  12439. * Gets an object containing information about the current webGL context
  12440. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12441. */
  12442. Engine.prototype.getGlInfo = function () {
  12443. return {
  12444. vendor: this._glVendor,
  12445. renderer: this._glRenderer,
  12446. version: this._glVersion
  12447. };
  12448. };
  12449. /**
  12450. * Gets current aspect ratio
  12451. * @param camera defines the camera to use to get the aspect ratio
  12452. * @param useScreen defines if screen size must be used (or the current render target if any)
  12453. * @returns a number defining the aspect ratio
  12454. */
  12455. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12456. if (useScreen === void 0) { useScreen = false; }
  12457. var viewport = camera.viewport;
  12458. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12459. };
  12460. /**
  12461. * Gets current screen aspect ratio
  12462. * @returns a number defining the aspect ratio
  12463. */
  12464. Engine.prototype.getScreenAspectRatio = function () {
  12465. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12466. };
  12467. /**
  12468. * Gets the current render width
  12469. * @param useScreen defines if screen size must be used (or the current render target if any)
  12470. * @returns a number defining the current render width
  12471. */
  12472. Engine.prototype.getRenderWidth = function (useScreen) {
  12473. if (useScreen === void 0) { useScreen = false; }
  12474. if (!useScreen && this._currentRenderTarget) {
  12475. return this._currentRenderTarget.width;
  12476. }
  12477. return this._gl.drawingBufferWidth;
  12478. };
  12479. /**
  12480. * Gets the current render height
  12481. * @param useScreen defines if screen size must be used (or the current render target if any)
  12482. * @returns a number defining the current render height
  12483. */
  12484. Engine.prototype.getRenderHeight = function (useScreen) {
  12485. if (useScreen === void 0) { useScreen = false; }
  12486. if (!useScreen && this._currentRenderTarget) {
  12487. return this._currentRenderTarget.height;
  12488. }
  12489. return this._gl.drawingBufferHeight;
  12490. };
  12491. /**
  12492. * Gets the HTML canvas attached with the current webGL context
  12493. * @returns a HTML canvas
  12494. */
  12495. Engine.prototype.getRenderingCanvas = function () {
  12496. return this._renderingCanvas;
  12497. };
  12498. /**
  12499. * Gets the client rect of the HTML canvas attached with the current webGL context
  12500. * @returns a client rectanglee
  12501. */
  12502. Engine.prototype.getRenderingCanvasClientRect = function () {
  12503. if (!this._renderingCanvas) {
  12504. return null;
  12505. }
  12506. return this._renderingCanvas.getBoundingClientRect();
  12507. };
  12508. /**
  12509. * Defines the hardware scaling level.
  12510. * By default the hardware scaling level is computed from the window device ratio.
  12511. * 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.
  12512. * @param level defines the level to use
  12513. */
  12514. Engine.prototype.setHardwareScalingLevel = function (level) {
  12515. this._hardwareScalingLevel = level;
  12516. this.resize();
  12517. };
  12518. /**
  12519. * Gets the current hardware scaling level.
  12520. * By default the hardware scaling level is computed from the window device ratio.
  12521. * 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.
  12522. * @returns a number indicating the current hardware scaling level
  12523. */
  12524. Engine.prototype.getHardwareScalingLevel = function () {
  12525. return this._hardwareScalingLevel;
  12526. };
  12527. /**
  12528. * Gets the list of loaded textures
  12529. * @returns an array containing all loaded textures
  12530. */
  12531. Engine.prototype.getLoadedTexturesCache = function () {
  12532. return this._internalTexturesCache;
  12533. };
  12534. /**
  12535. * Gets the object containing all engine capabilities
  12536. * @returns the EngineCapabilities object
  12537. */
  12538. Engine.prototype.getCaps = function () {
  12539. return this._caps;
  12540. };
  12541. Object.defineProperty(Engine.prototype, "drawCalls", {
  12542. /** @hidden */
  12543. get: function () {
  12544. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12545. return 0;
  12546. },
  12547. enumerable: true,
  12548. configurable: true
  12549. });
  12550. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12551. /** @hidden */
  12552. get: function () {
  12553. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12554. return null;
  12555. },
  12556. enumerable: true,
  12557. configurable: true
  12558. });
  12559. /**
  12560. * Gets the current depth function
  12561. * @returns a number defining the depth function
  12562. */
  12563. Engine.prototype.getDepthFunction = function () {
  12564. return this._depthCullingState.depthFunc;
  12565. };
  12566. /**
  12567. * Sets the current depth function
  12568. * @param depthFunc defines the function to use
  12569. */
  12570. Engine.prototype.setDepthFunction = function (depthFunc) {
  12571. this._depthCullingState.depthFunc = depthFunc;
  12572. };
  12573. /**
  12574. * Sets the current depth function to GREATER
  12575. */
  12576. Engine.prototype.setDepthFunctionToGreater = function () {
  12577. this._depthCullingState.depthFunc = this._gl.GREATER;
  12578. };
  12579. /**
  12580. * Sets the current depth function to GEQUAL
  12581. */
  12582. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12583. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12584. };
  12585. /**
  12586. * Sets the current depth function to LESS
  12587. */
  12588. Engine.prototype.setDepthFunctionToLess = function () {
  12589. this._depthCullingState.depthFunc = this._gl.LESS;
  12590. };
  12591. /**
  12592. * Sets the current depth function to LEQUAL
  12593. */
  12594. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12595. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12596. };
  12597. /**
  12598. * Gets a boolean indicating if stencil buffer is enabled
  12599. * @returns the current stencil buffer state
  12600. */
  12601. Engine.prototype.getStencilBuffer = function () {
  12602. return this._stencilState.stencilTest;
  12603. };
  12604. /**
  12605. * Enable or disable the stencil buffer
  12606. * @param enable defines if the stencil buffer must be enabled or disabled
  12607. */
  12608. Engine.prototype.setStencilBuffer = function (enable) {
  12609. this._stencilState.stencilTest = enable;
  12610. };
  12611. /**
  12612. * Gets the current stencil mask
  12613. * @returns a number defining the new stencil mask to use
  12614. */
  12615. Engine.prototype.getStencilMask = function () {
  12616. return this._stencilState.stencilMask;
  12617. };
  12618. /**
  12619. * Sets the current stencil mask
  12620. * @param mask defines the new stencil mask to use
  12621. */
  12622. Engine.prototype.setStencilMask = function (mask) {
  12623. this._stencilState.stencilMask = mask;
  12624. };
  12625. /**
  12626. * Gets the current stencil function
  12627. * @returns a number defining the stencil function to use
  12628. */
  12629. Engine.prototype.getStencilFunction = function () {
  12630. return this._stencilState.stencilFunc;
  12631. };
  12632. /**
  12633. * Gets the current stencil reference value
  12634. * @returns a number defining the stencil reference value to use
  12635. */
  12636. Engine.prototype.getStencilFunctionReference = function () {
  12637. return this._stencilState.stencilFuncRef;
  12638. };
  12639. /**
  12640. * Gets the current stencil mask
  12641. * @returns a number defining the stencil mask to use
  12642. */
  12643. Engine.prototype.getStencilFunctionMask = function () {
  12644. return this._stencilState.stencilFuncMask;
  12645. };
  12646. /**
  12647. * Sets the current stencil function
  12648. * @param stencilFunc defines the new stencil function to use
  12649. */
  12650. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12651. this._stencilState.stencilFunc = stencilFunc;
  12652. };
  12653. /**
  12654. * Sets the current stencil reference
  12655. * @param reference defines the new stencil reference to use
  12656. */
  12657. Engine.prototype.setStencilFunctionReference = function (reference) {
  12658. this._stencilState.stencilFuncRef = reference;
  12659. };
  12660. /**
  12661. * Sets the current stencil mask
  12662. * @param mask defines the new stencil mask to use
  12663. */
  12664. Engine.prototype.setStencilFunctionMask = function (mask) {
  12665. this._stencilState.stencilFuncMask = mask;
  12666. };
  12667. /**
  12668. * Gets the current stencil operation when stencil fails
  12669. * @returns a number defining stencil operation to use when stencil fails
  12670. */
  12671. Engine.prototype.getStencilOperationFail = function () {
  12672. return this._stencilState.stencilOpStencilFail;
  12673. };
  12674. /**
  12675. * Gets the current stencil operation when depth fails
  12676. * @returns a number defining stencil operation to use when depth fails
  12677. */
  12678. Engine.prototype.getStencilOperationDepthFail = function () {
  12679. return this._stencilState.stencilOpDepthFail;
  12680. };
  12681. /**
  12682. * Gets the current stencil operation when stencil passes
  12683. * @returns a number defining stencil operation to use when stencil passes
  12684. */
  12685. Engine.prototype.getStencilOperationPass = function () {
  12686. return this._stencilState.stencilOpStencilDepthPass;
  12687. };
  12688. /**
  12689. * Sets the stencil operation to use when stencil fails
  12690. * @param operation defines the stencil operation to use when stencil fails
  12691. */
  12692. Engine.prototype.setStencilOperationFail = function (operation) {
  12693. this._stencilState.stencilOpStencilFail = operation;
  12694. };
  12695. /**
  12696. * Sets the stencil operation to use when depth fails
  12697. * @param operation defines the stencil operation to use when depth fails
  12698. */
  12699. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12700. this._stencilState.stencilOpDepthFail = operation;
  12701. };
  12702. /**
  12703. * Sets the stencil operation to use when stencil passes
  12704. * @param operation defines the stencil operation to use when stencil passes
  12705. */
  12706. Engine.prototype.setStencilOperationPass = function (operation) {
  12707. this._stencilState.stencilOpStencilDepthPass = operation;
  12708. };
  12709. /**
  12710. * Sets a boolean indicating if the dithering state is enabled or disabled
  12711. * @param value defines the dithering state
  12712. */
  12713. Engine.prototype.setDitheringState = function (value) {
  12714. if (value) {
  12715. this._gl.enable(this._gl.DITHER);
  12716. }
  12717. else {
  12718. this._gl.disable(this._gl.DITHER);
  12719. }
  12720. };
  12721. /**
  12722. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12723. * @param value defines the rasterizer state
  12724. */
  12725. Engine.prototype.setRasterizerState = function (value) {
  12726. if (value) {
  12727. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12728. }
  12729. else {
  12730. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12731. }
  12732. };
  12733. /**
  12734. * stop executing a render loop function and remove it from the execution array
  12735. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12736. */
  12737. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12738. if (!renderFunction) {
  12739. this._activeRenderLoops = [];
  12740. return;
  12741. }
  12742. var index = this._activeRenderLoops.indexOf(renderFunction);
  12743. if (index >= 0) {
  12744. this._activeRenderLoops.splice(index, 1);
  12745. }
  12746. };
  12747. /** @hidden */
  12748. Engine.prototype._renderLoop = function () {
  12749. if (!this._contextWasLost) {
  12750. var shouldRender = true;
  12751. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12752. shouldRender = false;
  12753. }
  12754. if (shouldRender) {
  12755. // Start new frame
  12756. this.beginFrame();
  12757. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12758. var renderFunction = this._activeRenderLoops[index];
  12759. renderFunction();
  12760. }
  12761. // Present
  12762. this.endFrame();
  12763. }
  12764. }
  12765. if (this._activeRenderLoops.length > 0) {
  12766. // Register new frame
  12767. var requester = null;
  12768. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12769. requester = this._vrDisplay;
  12770. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12771. }
  12772. else {
  12773. this._renderingQueueLaunched = false;
  12774. }
  12775. };
  12776. /**
  12777. * Register and execute a render loop. The engine can have more than one render function
  12778. * @param renderFunction defines the function to continuously execute
  12779. */
  12780. Engine.prototype.runRenderLoop = function (renderFunction) {
  12781. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12782. return;
  12783. }
  12784. this._activeRenderLoops.push(renderFunction);
  12785. if (!this._renderingQueueLaunched) {
  12786. this._renderingQueueLaunched = true;
  12787. this._bindedRenderFunction = this._renderLoop.bind(this);
  12788. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12789. }
  12790. };
  12791. /**
  12792. * Toggle full screen mode
  12793. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12794. * @param options defines an option object to be sent to the requestFullscreen function
  12795. */
  12796. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12797. if (this.isFullscreen) {
  12798. BABYLON.Tools.ExitFullscreen();
  12799. }
  12800. else {
  12801. this._pointerLockRequested = requestPointerLock;
  12802. if (this._renderingCanvas) {
  12803. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12804. }
  12805. }
  12806. };
  12807. /**
  12808. * Clear the current render buffer or the current render target (if any is set up)
  12809. * @param color defines the color to use
  12810. * @param backBuffer defines if the back buffer must be cleared
  12811. * @param depth defines if the depth buffer must be cleared
  12812. * @param stencil defines if the stencil buffer must be cleared
  12813. */
  12814. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12815. if (stencil === void 0) { stencil = false; }
  12816. this.applyStates();
  12817. var mode = 0;
  12818. if (backBuffer && color) {
  12819. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12820. mode |= this._gl.COLOR_BUFFER_BIT;
  12821. }
  12822. if (depth) {
  12823. this._gl.clearDepth(1.0);
  12824. mode |= this._gl.DEPTH_BUFFER_BIT;
  12825. }
  12826. if (stencil) {
  12827. this._gl.clearStencil(0);
  12828. mode |= this._gl.STENCIL_BUFFER_BIT;
  12829. }
  12830. this._gl.clear(mode);
  12831. };
  12832. /**
  12833. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12834. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12835. * @param y defines the y-coordinate of the corner of the clear rectangle
  12836. * @param width defines the width of the clear rectangle
  12837. * @param height defines the height of the clear rectangle
  12838. * @param clearColor defines the clear color
  12839. */
  12840. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12841. var gl = this._gl;
  12842. // Save state
  12843. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12844. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12845. // Change state
  12846. gl.enable(gl.SCISSOR_TEST);
  12847. gl.scissor(x, y, width, height);
  12848. // Clear
  12849. this.clear(clearColor, true, true, true);
  12850. // Restore state
  12851. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12852. if (curScissor === true) {
  12853. gl.enable(gl.SCISSOR_TEST);
  12854. }
  12855. else {
  12856. gl.disable(gl.SCISSOR_TEST);
  12857. }
  12858. };
  12859. /**
  12860. * Set the WebGL's viewport
  12861. * @param viewport defines the viewport element to be used
  12862. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12863. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12864. */
  12865. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12866. var width = requiredWidth || this.getRenderWidth();
  12867. var height = requiredHeight || this.getRenderHeight();
  12868. var x = viewport.x || 0;
  12869. var y = viewport.y || 0;
  12870. this._cachedViewport = viewport;
  12871. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12872. };
  12873. /**
  12874. * Directly set the WebGL Viewport
  12875. * @param x defines the x coordinate of the viewport (in screen space)
  12876. * @param y defines the y coordinate of the viewport (in screen space)
  12877. * @param width defines the width of the viewport (in screen space)
  12878. * @param height defines the height of the viewport (in screen space)
  12879. * @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
  12880. */
  12881. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12882. var currentViewport = this._cachedViewport;
  12883. this._cachedViewport = null;
  12884. this._gl.viewport(x, y, width, height);
  12885. return currentViewport;
  12886. };
  12887. /**
  12888. * Begin a new frame
  12889. */
  12890. Engine.prototype.beginFrame = function () {
  12891. this.onBeginFrameObservable.notifyObservers(this);
  12892. this._measureFps();
  12893. };
  12894. /**
  12895. * Enf the current frame
  12896. */
  12897. Engine.prototype.endFrame = function () {
  12898. // Force a flush in case we are using a bad OS.
  12899. if (this._badOS) {
  12900. this.flushFramebuffer();
  12901. }
  12902. // Submit frame to the vr device, if enabled
  12903. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12904. // TODO: We should only submit the frame if we read frameData successfully.
  12905. this._vrDisplay.submitFrame();
  12906. }
  12907. this.onEndFrameObservable.notifyObservers(this);
  12908. };
  12909. /**
  12910. * Resize the view according to the canvas' size
  12911. */
  12912. Engine.prototype.resize = function () {
  12913. // We're not resizing the size of the canvas while in VR mode & presenting
  12914. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12915. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12916. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12917. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12918. }
  12919. };
  12920. /**
  12921. * Force a specific size of the canvas
  12922. * @param width defines the new canvas' width
  12923. * @param height defines the new canvas' height
  12924. */
  12925. Engine.prototype.setSize = function (width, height) {
  12926. if (!this._renderingCanvas) {
  12927. return;
  12928. }
  12929. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12930. return;
  12931. }
  12932. this._renderingCanvas.width = width;
  12933. this._renderingCanvas.height = height;
  12934. for (var index = 0; index < this.scenes.length; index++) {
  12935. var scene = this.scenes[index];
  12936. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12937. var cam = scene.cameras[camIndex];
  12938. cam._currentRenderId = 0;
  12939. }
  12940. }
  12941. if (this.onResizeObservable.hasObservers) {
  12942. this.onResizeObservable.notifyObservers(this);
  12943. }
  12944. };
  12945. // WebVR functions
  12946. /**
  12947. * Gets a boolean indicating if a webVR device was detected
  12948. * @returns true if a webVR device was detected
  12949. */
  12950. Engine.prototype.isVRDevicePresent = function () {
  12951. return !!this._vrDisplay;
  12952. };
  12953. /**
  12954. * Gets the current webVR device
  12955. * @returns the current webVR device (or null)
  12956. */
  12957. Engine.prototype.getVRDevice = function () {
  12958. return this._vrDisplay;
  12959. };
  12960. /**
  12961. * Initializes a webVR display and starts listening to display change events
  12962. * The onVRDisplayChangedObservable will be notified upon these changes
  12963. * @returns The onVRDisplayChangedObservable
  12964. */
  12965. Engine.prototype.initWebVR = function () {
  12966. this.initWebVRAsync();
  12967. return this.onVRDisplayChangedObservable;
  12968. };
  12969. /**
  12970. * Initializes a webVR display and starts listening to display change events
  12971. * The onVRDisplayChangedObservable will be notified upon these changes
  12972. * @returns A promise containing a VRDisplay and if vr is supported
  12973. */
  12974. Engine.prototype.initWebVRAsync = function () {
  12975. var _this = this;
  12976. var notifyObservers = function () {
  12977. var eventArgs = {
  12978. vrDisplay: _this._vrDisplay,
  12979. vrSupported: _this._vrSupported
  12980. };
  12981. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12982. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12983. };
  12984. if (!this._onVrDisplayConnect) {
  12985. this._onVrDisplayConnect = function (event) {
  12986. _this._vrDisplay = event.display;
  12987. notifyObservers();
  12988. };
  12989. this._onVrDisplayDisconnect = function () {
  12990. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12991. _this._vrDisplay = undefined;
  12992. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12993. notifyObservers();
  12994. };
  12995. this._onVrDisplayPresentChange = function () {
  12996. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12997. };
  12998. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12999. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13000. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13001. }
  13002. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13003. this._webVRInitPromise.then(notifyObservers);
  13004. return this._webVRInitPromise;
  13005. };
  13006. /**
  13007. * Call this function to switch to webVR mode
  13008. * Will do nothing if webVR is not supported or if there is no webVR device
  13009. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13010. */
  13011. Engine.prototype.enableVR = function () {
  13012. var _this = this;
  13013. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13014. var onResolved = function () {
  13015. _this.onVRRequestPresentComplete.notifyObservers(true);
  13016. _this._onVRFullScreenTriggered();
  13017. };
  13018. var onRejected = function () {
  13019. _this.onVRRequestPresentComplete.notifyObservers(false);
  13020. };
  13021. this.onVRRequestPresentStart.notifyObservers(this);
  13022. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13023. }
  13024. };
  13025. /**
  13026. * Call this function to leave webVR mode
  13027. * Will do nothing if webVR is not supported or if there is no webVR device
  13028. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13029. */
  13030. Engine.prototype.disableVR = function () {
  13031. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13032. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13033. }
  13034. };
  13035. Engine.prototype._getVRDisplaysAsync = function () {
  13036. var _this = this;
  13037. return new Promise(function (res, rej) {
  13038. if (navigator.getVRDisplays) {
  13039. navigator.getVRDisplays().then(function (devices) {
  13040. _this._vrSupported = true;
  13041. // note that devices may actually be an empty array. This is fine;
  13042. // we expect this._vrDisplay to be undefined in this case.
  13043. _this._vrDisplay = devices[0];
  13044. res({
  13045. vrDisplay: _this._vrDisplay,
  13046. vrSupported: _this._vrSupported
  13047. });
  13048. });
  13049. }
  13050. else {
  13051. _this._vrDisplay = undefined;
  13052. _this._vrSupported = false;
  13053. res({
  13054. vrDisplay: _this._vrDisplay,
  13055. vrSupported: _this._vrSupported
  13056. });
  13057. }
  13058. });
  13059. };
  13060. /**
  13061. * Binds the frame buffer to the specified texture.
  13062. * @param texture The texture to render to or null for the default canvas
  13063. * @param faceIndex The face of the texture to render to in case of cube texture
  13064. * @param requiredWidth The width of the target to render to
  13065. * @param requiredHeight The height of the target to render to
  13066. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13067. * @param depthStencilTexture The depth stencil texture to use to render
  13068. * @param lodLevel defines le lod level to bind to the frame buffer
  13069. */
  13070. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13071. if (lodLevel === void 0) { lodLevel = 0; }
  13072. if (this._currentRenderTarget) {
  13073. this.unBindFramebuffer(this._currentRenderTarget);
  13074. }
  13075. this._currentRenderTarget = texture;
  13076. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13077. var gl = this._gl;
  13078. if (texture.isCube) {
  13079. if (faceIndex === undefined) {
  13080. faceIndex = 0;
  13081. }
  13082. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13083. if (depthStencilTexture) {
  13084. if (depthStencilTexture._generateStencilBuffer) {
  13085. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13086. }
  13087. else {
  13088. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13089. }
  13090. }
  13091. }
  13092. if (this._cachedViewport && !forceFullscreenViewport) {
  13093. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13094. }
  13095. else {
  13096. if (!requiredWidth) {
  13097. requiredWidth = texture.width;
  13098. if (lodLevel) {
  13099. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13100. }
  13101. }
  13102. if (!requiredHeight) {
  13103. requiredHeight = texture.height;
  13104. if (lodLevel) {
  13105. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13106. }
  13107. }
  13108. gl.viewport(0, 0, requiredWidth, requiredHeight);
  13109. }
  13110. this.wipeCaches();
  13111. };
  13112. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13113. if (this._currentFramebuffer !== framebuffer) {
  13114. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13115. this._currentFramebuffer = framebuffer;
  13116. }
  13117. };
  13118. /**
  13119. * Unbind the current render target texture from the webGL context
  13120. * @param texture defines the render target texture to unbind
  13121. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13122. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13123. */
  13124. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13125. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13126. this._currentRenderTarget = null;
  13127. // If MSAA, we need to bitblt back to main texture
  13128. var gl = this._gl;
  13129. if (texture._MSAAFramebuffer) {
  13130. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13131. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13132. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13133. }
  13134. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13135. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13136. gl.generateMipmap(gl.TEXTURE_2D);
  13137. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13138. }
  13139. if (onBeforeUnbind) {
  13140. if (texture._MSAAFramebuffer) {
  13141. // Bind the correct framebuffer
  13142. this.bindUnboundFramebuffer(texture._framebuffer);
  13143. }
  13144. onBeforeUnbind();
  13145. }
  13146. this.bindUnboundFramebuffer(null);
  13147. };
  13148. /**
  13149. * Unbind a list of render target textures from the webGL context
  13150. * This is used only when drawBuffer extension or webGL2 are active
  13151. * @param textures defines the render target textures to unbind
  13152. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13153. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13154. */
  13155. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13156. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13157. this._currentRenderTarget = null;
  13158. // If MSAA, we need to bitblt back to main texture
  13159. var gl = this._gl;
  13160. if (textures[0]._MSAAFramebuffer) {
  13161. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13162. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13163. var attachments = textures[0]._attachments;
  13164. if (!attachments) {
  13165. attachments = new Array(textures.length);
  13166. textures[0]._attachments = attachments;
  13167. }
  13168. for (var i = 0; i < textures.length; i++) {
  13169. var texture = textures[i];
  13170. for (var j = 0; j < attachments.length; j++) {
  13171. attachments[j] = gl.NONE;
  13172. }
  13173. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13174. gl.readBuffer(attachments[i]);
  13175. gl.drawBuffers(attachments);
  13176. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13177. }
  13178. for (var i = 0; i < attachments.length; i++) {
  13179. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13180. }
  13181. gl.drawBuffers(attachments);
  13182. }
  13183. for (var i = 0; i < textures.length; i++) {
  13184. var texture = textures[i];
  13185. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13186. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13187. gl.generateMipmap(gl.TEXTURE_2D);
  13188. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13189. }
  13190. }
  13191. if (onBeforeUnbind) {
  13192. if (textures[0]._MSAAFramebuffer) {
  13193. // Bind the correct framebuffer
  13194. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13195. }
  13196. onBeforeUnbind();
  13197. }
  13198. this.bindUnboundFramebuffer(null);
  13199. };
  13200. /**
  13201. * Force the mipmap generation for the given render target texture
  13202. * @param texture defines the render target texture to use
  13203. */
  13204. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13205. if (texture.generateMipMaps) {
  13206. var gl = this._gl;
  13207. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13208. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13209. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13210. }
  13211. };
  13212. /**
  13213. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13214. */
  13215. Engine.prototype.flushFramebuffer = function () {
  13216. this._gl.flush();
  13217. };
  13218. /**
  13219. * Unbind the current render target and bind the default framebuffer
  13220. */
  13221. Engine.prototype.restoreDefaultFramebuffer = function () {
  13222. if (this._currentRenderTarget) {
  13223. this.unBindFramebuffer(this._currentRenderTarget);
  13224. }
  13225. else {
  13226. this.bindUnboundFramebuffer(null);
  13227. }
  13228. if (this._cachedViewport) {
  13229. this.setViewport(this._cachedViewport);
  13230. }
  13231. this.wipeCaches();
  13232. };
  13233. // UBOs
  13234. /**
  13235. * Create an uniform buffer
  13236. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13237. * @param elements defines the content of the uniform buffer
  13238. * @returns the webGL uniform buffer
  13239. */
  13240. Engine.prototype.createUniformBuffer = function (elements) {
  13241. var ubo = this._gl.createBuffer();
  13242. if (!ubo) {
  13243. throw new Error("Unable to create uniform buffer");
  13244. }
  13245. this.bindUniformBuffer(ubo);
  13246. if (elements instanceof Float32Array) {
  13247. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13248. }
  13249. else {
  13250. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13251. }
  13252. this.bindUniformBuffer(null);
  13253. ubo.references = 1;
  13254. return ubo;
  13255. };
  13256. /**
  13257. * Create a dynamic uniform buffer
  13258. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13259. * @param elements defines the content of the uniform buffer
  13260. * @returns the webGL uniform buffer
  13261. */
  13262. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13263. var ubo = this._gl.createBuffer();
  13264. if (!ubo) {
  13265. throw new Error("Unable to create dynamic uniform buffer");
  13266. }
  13267. this.bindUniformBuffer(ubo);
  13268. if (elements instanceof Float32Array) {
  13269. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13270. }
  13271. else {
  13272. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13273. }
  13274. this.bindUniformBuffer(null);
  13275. ubo.references = 1;
  13276. return ubo;
  13277. };
  13278. /**
  13279. * Update an existing uniform buffer
  13280. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13281. * @param uniformBuffer defines the target uniform buffer
  13282. * @param elements defines the content to update
  13283. * @param offset defines the offset in the uniform buffer where update should start
  13284. * @param count defines the size of the data to update
  13285. */
  13286. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13287. this.bindUniformBuffer(uniformBuffer);
  13288. if (offset === undefined) {
  13289. offset = 0;
  13290. }
  13291. if (count === undefined) {
  13292. if (elements instanceof Float32Array) {
  13293. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13294. }
  13295. else {
  13296. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13297. }
  13298. }
  13299. else {
  13300. if (elements instanceof Float32Array) {
  13301. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13302. }
  13303. else {
  13304. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13305. }
  13306. }
  13307. this.bindUniformBuffer(null);
  13308. };
  13309. // VBOs
  13310. Engine.prototype._resetVertexBufferBinding = function () {
  13311. this.bindArrayBuffer(null);
  13312. this._cachedVertexBuffers = null;
  13313. };
  13314. /**
  13315. * Creates a vertex buffer
  13316. * @param data the data for the vertex buffer
  13317. * @returns the new WebGL static buffer
  13318. */
  13319. Engine.prototype.createVertexBuffer = function (data) {
  13320. var vbo = this._gl.createBuffer();
  13321. if (!vbo) {
  13322. throw new Error("Unable to create vertex buffer");
  13323. }
  13324. this.bindArrayBuffer(vbo);
  13325. if (data instanceof Array) {
  13326. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13327. }
  13328. else {
  13329. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13330. }
  13331. this._resetVertexBufferBinding();
  13332. vbo.references = 1;
  13333. return vbo;
  13334. };
  13335. /**
  13336. * Creates a dynamic vertex buffer
  13337. * @param data the data for the dynamic vertex buffer
  13338. * @returns the new WebGL dynamic buffer
  13339. */
  13340. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13341. var vbo = this._gl.createBuffer();
  13342. if (!vbo) {
  13343. throw new Error("Unable to create dynamic vertex buffer");
  13344. }
  13345. this.bindArrayBuffer(vbo);
  13346. if (data instanceof Array) {
  13347. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13348. }
  13349. else {
  13350. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13351. }
  13352. this._resetVertexBufferBinding();
  13353. vbo.references = 1;
  13354. return vbo;
  13355. };
  13356. /**
  13357. * Update a dynamic index buffer
  13358. * @param indexBuffer defines the target index buffer
  13359. * @param indices defines the data to update
  13360. * @param offset defines the offset in the target index buffer where update should start
  13361. */
  13362. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13363. if (offset === void 0) { offset = 0; }
  13364. // Force cache update
  13365. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13366. this.bindIndexBuffer(indexBuffer);
  13367. var arrayBuffer;
  13368. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13369. arrayBuffer = indices;
  13370. }
  13371. else {
  13372. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13373. }
  13374. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13375. this._resetIndexBufferBinding();
  13376. };
  13377. /**
  13378. * Updates a dynamic vertex buffer.
  13379. * @param vertexBuffer the vertex buffer to update
  13380. * @param data the data used to update the vertex buffer
  13381. * @param byteOffset the byte offset of the data
  13382. * @param byteLength the byte length of the data
  13383. */
  13384. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13385. this.bindArrayBuffer(vertexBuffer);
  13386. if (byteOffset === undefined) {
  13387. byteOffset = 0;
  13388. }
  13389. if (byteLength === undefined) {
  13390. if (data instanceof Array) {
  13391. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13392. }
  13393. else {
  13394. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13395. }
  13396. }
  13397. else {
  13398. if (data instanceof Array) {
  13399. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13400. }
  13401. else {
  13402. if (data instanceof ArrayBuffer) {
  13403. data = new Uint8Array(data, byteOffset, byteLength);
  13404. }
  13405. else {
  13406. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13407. }
  13408. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13409. }
  13410. }
  13411. this._resetVertexBufferBinding();
  13412. };
  13413. Engine.prototype._resetIndexBufferBinding = function () {
  13414. this.bindIndexBuffer(null);
  13415. this._cachedIndexBuffer = null;
  13416. };
  13417. /**
  13418. * Creates a new index buffer
  13419. * @param indices defines the content of the index buffer
  13420. * @param updatable defines if the index buffer must be updatable
  13421. * @returns a new webGL buffer
  13422. */
  13423. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13424. var vbo = this._gl.createBuffer();
  13425. if (!vbo) {
  13426. throw new Error("Unable to create index buffer");
  13427. }
  13428. this.bindIndexBuffer(vbo);
  13429. // Check for 32 bits indices
  13430. var arrayBuffer;
  13431. var need32Bits = false;
  13432. if (indices instanceof Uint16Array) {
  13433. arrayBuffer = indices;
  13434. }
  13435. else {
  13436. //check 32 bit support
  13437. if (this._caps.uintIndices) {
  13438. if (indices instanceof Uint32Array) {
  13439. arrayBuffer = indices;
  13440. need32Bits = true;
  13441. }
  13442. else {
  13443. //number[] or Int32Array, check if 32 bit is necessary
  13444. for (var index = 0; index < indices.length; index++) {
  13445. if (indices[index] > 65535) {
  13446. need32Bits = true;
  13447. break;
  13448. }
  13449. }
  13450. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13451. }
  13452. }
  13453. else {
  13454. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13455. arrayBuffer = new Uint16Array(indices);
  13456. }
  13457. }
  13458. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13459. this._resetIndexBufferBinding();
  13460. vbo.references = 1;
  13461. vbo.is32Bits = need32Bits;
  13462. return vbo;
  13463. };
  13464. /**
  13465. * Bind a webGL buffer to the webGL context
  13466. * @param buffer defines the buffer to bind
  13467. */
  13468. Engine.prototype.bindArrayBuffer = function (buffer) {
  13469. if (!this._vaoRecordInProgress) {
  13470. this._unbindVertexArrayObject();
  13471. }
  13472. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13473. };
  13474. /**
  13475. * Bind an uniform buffer to the current webGL context
  13476. * @param buffer defines the buffer to bind
  13477. */
  13478. Engine.prototype.bindUniformBuffer = function (buffer) {
  13479. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13480. };
  13481. /**
  13482. * Bind a buffer to the current webGL context at a given location
  13483. * @param buffer defines the buffer to bind
  13484. * @param location defines the index where to bind the buffer
  13485. */
  13486. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13487. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13488. };
  13489. /**
  13490. * Bind a specific block at a given index in a specific shader program
  13491. * @param shaderProgram defines the shader program
  13492. * @param blockName defines the block name
  13493. * @param index defines the index where to bind the block
  13494. */
  13495. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13496. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13497. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13498. };
  13499. ;
  13500. Engine.prototype.bindIndexBuffer = function (buffer) {
  13501. if (!this._vaoRecordInProgress) {
  13502. this._unbindVertexArrayObject();
  13503. }
  13504. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13505. };
  13506. Engine.prototype.bindBuffer = function (buffer, target) {
  13507. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13508. this._gl.bindBuffer(target, buffer);
  13509. this._currentBoundBuffer[target] = buffer;
  13510. }
  13511. };
  13512. /**
  13513. * update the bound buffer with the given data
  13514. * @param data defines the data to update
  13515. */
  13516. Engine.prototype.updateArrayBuffer = function (data) {
  13517. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13518. };
  13519. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13520. var pointer = this._currentBufferPointers[indx];
  13521. var changed = false;
  13522. if (!pointer.active) {
  13523. changed = true;
  13524. pointer.active = true;
  13525. pointer.index = indx;
  13526. pointer.size = size;
  13527. pointer.type = type;
  13528. pointer.normalized = normalized;
  13529. pointer.stride = stride;
  13530. pointer.offset = offset;
  13531. pointer.buffer = buffer;
  13532. }
  13533. else {
  13534. if (pointer.buffer !== buffer) {
  13535. pointer.buffer = buffer;
  13536. changed = true;
  13537. }
  13538. if (pointer.size !== size) {
  13539. pointer.size = size;
  13540. changed = true;
  13541. }
  13542. if (pointer.type !== type) {
  13543. pointer.type = type;
  13544. changed = true;
  13545. }
  13546. if (pointer.normalized !== normalized) {
  13547. pointer.normalized = normalized;
  13548. changed = true;
  13549. }
  13550. if (pointer.stride !== stride) {
  13551. pointer.stride = stride;
  13552. changed = true;
  13553. }
  13554. if (pointer.offset !== offset) {
  13555. pointer.offset = offset;
  13556. changed = true;
  13557. }
  13558. }
  13559. if (changed || this._vaoRecordInProgress) {
  13560. this.bindArrayBuffer(buffer);
  13561. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13562. }
  13563. };
  13564. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13565. if (indexBuffer == null) {
  13566. return;
  13567. }
  13568. if (this._cachedIndexBuffer !== indexBuffer) {
  13569. this._cachedIndexBuffer = indexBuffer;
  13570. this.bindIndexBuffer(indexBuffer);
  13571. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13572. }
  13573. };
  13574. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13575. var attributes = effect.getAttributesNames();
  13576. if (!this._vaoRecordInProgress) {
  13577. this._unbindVertexArrayObject();
  13578. }
  13579. this.unbindAllAttributes();
  13580. for (var index = 0; index < attributes.length; index++) {
  13581. var order = effect.getAttributeLocation(index);
  13582. if (order >= 0) {
  13583. var vertexBuffer = vertexBuffers[attributes[index]];
  13584. if (!vertexBuffer) {
  13585. continue;
  13586. }
  13587. this._gl.enableVertexAttribArray(order);
  13588. if (!this._vaoRecordInProgress) {
  13589. this._vertexAttribArraysEnabled[order] = true;
  13590. }
  13591. var buffer = vertexBuffer.getBuffer();
  13592. if (buffer) {
  13593. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13594. if (vertexBuffer.getIsInstanced()) {
  13595. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13596. if (!this._vaoRecordInProgress) {
  13597. this._currentInstanceLocations.push(order);
  13598. this._currentInstanceBuffers.push(buffer);
  13599. }
  13600. }
  13601. }
  13602. }
  13603. }
  13604. };
  13605. /**
  13606. * Records a vertex array object
  13607. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13608. * @param vertexBuffers defines the list of vertex buffers to store
  13609. * @param indexBuffer defines the index buffer to store
  13610. * @param effect defines the effect to store
  13611. * @returns the new vertex array object
  13612. */
  13613. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13614. var vao = this._gl.createVertexArray();
  13615. this._vaoRecordInProgress = true;
  13616. this._gl.bindVertexArray(vao);
  13617. this._mustWipeVertexAttributes = true;
  13618. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13619. this.bindIndexBuffer(indexBuffer);
  13620. this._vaoRecordInProgress = false;
  13621. this._gl.bindVertexArray(null);
  13622. return vao;
  13623. };
  13624. /**
  13625. * Bind a specific vertex array object
  13626. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13627. * @param vertexArrayObject defines the vertex array object to bind
  13628. * @param indexBuffer defines the index buffer to bind
  13629. */
  13630. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13631. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13632. this._cachedVertexArrayObject = vertexArrayObject;
  13633. this._gl.bindVertexArray(vertexArrayObject);
  13634. this._cachedVertexBuffers = null;
  13635. this._cachedIndexBuffer = null;
  13636. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13637. this._mustWipeVertexAttributes = true;
  13638. }
  13639. };
  13640. /**
  13641. * Bind webGl buffers directly to the webGL context
  13642. * @param vertexBuffer defines the vertex buffer to bind
  13643. * @param indexBuffer defines the index buffer to bind
  13644. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13645. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13646. * @param effect defines the effect associated with the vertex buffer
  13647. */
  13648. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13649. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13650. this._cachedVertexBuffers = vertexBuffer;
  13651. this._cachedEffectForVertexBuffers = effect;
  13652. var attributesCount = effect.getAttributesCount();
  13653. this._unbindVertexArrayObject();
  13654. this.unbindAllAttributes();
  13655. var offset = 0;
  13656. for (var index = 0; index < attributesCount; index++) {
  13657. if (index < vertexDeclaration.length) {
  13658. var order = effect.getAttributeLocation(index);
  13659. if (order >= 0) {
  13660. this._gl.enableVertexAttribArray(order);
  13661. this._vertexAttribArraysEnabled[order] = true;
  13662. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13663. }
  13664. offset += vertexDeclaration[index] * 4;
  13665. }
  13666. }
  13667. }
  13668. this._bindIndexBufferWithCache(indexBuffer);
  13669. };
  13670. Engine.prototype._unbindVertexArrayObject = function () {
  13671. if (!this._cachedVertexArrayObject) {
  13672. return;
  13673. }
  13674. this._cachedVertexArrayObject = null;
  13675. this._gl.bindVertexArray(null);
  13676. };
  13677. /**
  13678. * Bind a list of vertex buffers to the webGL context
  13679. * @param vertexBuffers defines the list of vertex buffers to bind
  13680. * @param indexBuffer defines the index buffer to bind
  13681. * @param effect defines the effect associated with the vertex buffers
  13682. */
  13683. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13684. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13685. this._cachedVertexBuffers = vertexBuffers;
  13686. this._cachedEffectForVertexBuffers = effect;
  13687. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13688. }
  13689. this._bindIndexBufferWithCache(indexBuffer);
  13690. };
  13691. /**
  13692. * Unbind all instance attributes
  13693. */
  13694. Engine.prototype.unbindInstanceAttributes = function () {
  13695. var boundBuffer;
  13696. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13697. var instancesBuffer = this._currentInstanceBuffers[i];
  13698. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13699. boundBuffer = instancesBuffer;
  13700. this.bindArrayBuffer(instancesBuffer);
  13701. }
  13702. var offsetLocation = this._currentInstanceLocations[i];
  13703. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13704. }
  13705. this._currentInstanceBuffers.length = 0;
  13706. this._currentInstanceLocations.length = 0;
  13707. };
  13708. /**
  13709. * Release and free the memory of a vertex array object
  13710. * @param vao defines the vertex array object to delete
  13711. */
  13712. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13713. this._gl.deleteVertexArray(vao);
  13714. };
  13715. /** @hidden */
  13716. Engine.prototype._releaseBuffer = function (buffer) {
  13717. buffer.references--;
  13718. if (buffer.references === 0) {
  13719. this._gl.deleteBuffer(buffer);
  13720. return true;
  13721. }
  13722. return false;
  13723. };
  13724. /**
  13725. * Creates a webGL buffer to use with instanciation
  13726. * @param capacity defines the size of the buffer
  13727. * @returns the webGL buffer
  13728. */
  13729. Engine.prototype.createInstancesBuffer = function (capacity) {
  13730. var buffer = this._gl.createBuffer();
  13731. if (!buffer) {
  13732. throw new Error("Unable to create instance buffer");
  13733. }
  13734. buffer.capacity = capacity;
  13735. this.bindArrayBuffer(buffer);
  13736. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13737. return buffer;
  13738. };
  13739. /**
  13740. * Delete a webGL buffer used with instanciation
  13741. * @param buffer defines the webGL buffer to delete
  13742. */
  13743. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13744. this._gl.deleteBuffer(buffer);
  13745. };
  13746. /**
  13747. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13748. * @param instancesBuffer defines the webGL buffer to update and bind
  13749. * @param data defines the data to store in the buffer
  13750. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13751. */
  13752. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13753. this.bindArrayBuffer(instancesBuffer);
  13754. if (data) {
  13755. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13756. }
  13757. if (offsetLocations[0].index !== undefined) {
  13758. var stride = 0;
  13759. for (var i = 0; i < offsetLocations.length; i++) {
  13760. var ai = offsetLocations[i];
  13761. stride += ai.attributeSize * 4;
  13762. }
  13763. for (var i = 0; i < offsetLocations.length; i++) {
  13764. var ai = offsetLocations[i];
  13765. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13766. this._gl.enableVertexAttribArray(ai.index);
  13767. this._vertexAttribArraysEnabled[ai.index] = true;
  13768. }
  13769. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13770. this._gl.vertexAttribDivisor(ai.index, 1);
  13771. this._currentInstanceLocations.push(ai.index);
  13772. this._currentInstanceBuffers.push(instancesBuffer);
  13773. }
  13774. }
  13775. else {
  13776. for (var index = 0; index < 4; index++) {
  13777. var offsetLocation = offsetLocations[index];
  13778. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13779. this._gl.enableVertexAttribArray(offsetLocation);
  13780. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13781. }
  13782. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13783. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13784. this._currentInstanceLocations.push(offsetLocation);
  13785. this._currentInstanceBuffers.push(instancesBuffer);
  13786. }
  13787. }
  13788. };
  13789. /**
  13790. * Apply all cached states (depth, culling, stencil and alpha)
  13791. */
  13792. Engine.prototype.applyStates = function () {
  13793. this._depthCullingState.apply(this._gl);
  13794. this._stencilState.apply(this._gl);
  13795. this._alphaState.apply(this._gl);
  13796. };
  13797. /**
  13798. * Send a draw order
  13799. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13800. * @param indexStart defines the starting index
  13801. * @param indexCount defines the number of index to draw
  13802. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13803. */
  13804. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13805. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13806. };
  13807. /**
  13808. * Draw a list of points
  13809. * @param verticesStart defines the index of first vertex to draw
  13810. * @param verticesCount defines the count of vertices to draw
  13811. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13812. */
  13813. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13814. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13815. };
  13816. /**
  13817. * Draw a list of unindexed primitives
  13818. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13819. * @param verticesStart defines the index of first vertex to draw
  13820. * @param verticesCount defines the count of vertices to draw
  13821. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13822. */
  13823. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13824. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13825. };
  13826. /**
  13827. * Draw a list of indexed primitives
  13828. * @param fillMode defines the primitive to use
  13829. * @param indexStart defines the starting index
  13830. * @param indexCount defines the number of index to draw
  13831. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13832. */
  13833. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13834. // Apply states
  13835. this.applyStates();
  13836. this._drawCalls.addCount(1, false);
  13837. // Render
  13838. var drawMode = this._drawMode(fillMode);
  13839. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13840. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13841. if (instancesCount) {
  13842. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13843. }
  13844. else {
  13845. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13846. }
  13847. };
  13848. /**
  13849. * Draw a list of unindexed primitives
  13850. * @param fillMode defines the primitive to use
  13851. * @param verticesStart defines the index of first vertex to draw
  13852. * @param verticesCount defines the count of vertices to draw
  13853. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13854. */
  13855. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13856. // Apply states
  13857. this.applyStates();
  13858. this._drawCalls.addCount(1, false);
  13859. var drawMode = this._drawMode(fillMode);
  13860. if (instancesCount) {
  13861. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13862. }
  13863. else {
  13864. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13865. }
  13866. };
  13867. Engine.prototype._drawMode = function (fillMode) {
  13868. switch (fillMode) {
  13869. // Triangle views
  13870. case BABYLON.Material.TriangleFillMode:
  13871. return this._gl.TRIANGLES;
  13872. case BABYLON.Material.PointFillMode:
  13873. return this._gl.POINTS;
  13874. case BABYLON.Material.WireFrameFillMode:
  13875. return this._gl.LINES;
  13876. // Draw modes
  13877. case BABYLON.Material.PointListDrawMode:
  13878. return this._gl.POINTS;
  13879. case BABYLON.Material.LineListDrawMode:
  13880. return this._gl.LINES;
  13881. case BABYLON.Material.LineLoopDrawMode:
  13882. return this._gl.LINE_LOOP;
  13883. case BABYLON.Material.LineStripDrawMode:
  13884. return this._gl.LINE_STRIP;
  13885. case BABYLON.Material.TriangleStripDrawMode:
  13886. return this._gl.TRIANGLE_STRIP;
  13887. case BABYLON.Material.TriangleFanDrawMode:
  13888. return this._gl.TRIANGLE_FAN;
  13889. default:
  13890. return this._gl.TRIANGLES;
  13891. }
  13892. };
  13893. // Shaders
  13894. /** @hidden */
  13895. Engine.prototype._releaseEffect = function (effect) {
  13896. if (this._compiledEffects[effect._key]) {
  13897. delete this._compiledEffects[effect._key];
  13898. this._deleteProgram(effect.getProgram());
  13899. }
  13900. };
  13901. /** @hidden */
  13902. Engine.prototype._deleteProgram = function (program) {
  13903. if (program) {
  13904. program.__SPECTOR_rebuildProgram = null;
  13905. if (program.transformFeedback) {
  13906. this.deleteTransformFeedback(program.transformFeedback);
  13907. program.transformFeedback = null;
  13908. }
  13909. this._gl.deleteProgram(program);
  13910. }
  13911. };
  13912. /**
  13913. * Create a new effect (used to store vertex/fragment shaders)
  13914. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13915. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13916. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13917. * @param samplers defines an array of string used to represent textures
  13918. * @param defines defines the string containing the defines to use to compile the shaders
  13919. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13920. * @param onCompiled defines a function to call when the effect creation is successful
  13921. * @param onError defines a function to call when the effect creation has failed
  13922. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13923. * @returns the new Effect
  13924. */
  13925. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13926. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13927. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13928. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13929. if (this._compiledEffects[name]) {
  13930. var compiledEffect = this._compiledEffects[name];
  13931. if (onCompiled && compiledEffect.isReady()) {
  13932. onCompiled(compiledEffect);
  13933. }
  13934. return compiledEffect;
  13935. }
  13936. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13937. effect._key = name;
  13938. this._compiledEffects[name] = effect;
  13939. return effect;
  13940. };
  13941. /**
  13942. * Create an effect to use with particle systems
  13943. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13944. * @param uniformsNames defines a list of attribute names
  13945. * @param samplers defines an array of string used to represent textures
  13946. * @param defines defines the string containing the defines to use to compile the shaders
  13947. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13948. * @param onCompiled defines a function to call when the effect creation is successful
  13949. * @param onError defines a function to call when the effect creation has failed
  13950. * @returns the new Effect
  13951. */
  13952. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13953. if (uniformsNames === void 0) { uniformsNames = []; }
  13954. if (samplers === void 0) { samplers = []; }
  13955. if (defines === void 0) { defines = ""; }
  13956. return this.createEffect({
  13957. vertex: "particles",
  13958. fragmentElement: fragmentName
  13959. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13960. };
  13961. /**
  13962. * Directly creates a webGL program
  13963. * @param vertexCode defines the vertex shader code to use
  13964. * @param fragmentCode defines the fragment shader code to use
  13965. * @param context defines the webGL context to use (if not set, the current one will be used)
  13966. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13967. * @returns the new webGL program
  13968. */
  13969. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13970. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13971. context = context || this._gl;
  13972. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13973. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13974. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13975. };
  13976. /**
  13977. * Creates a webGL program
  13978. * @param vertexCode defines the vertex shader code to use
  13979. * @param fragmentCode defines the fragment shader code to use
  13980. * @param defines defines the string containing the defines to use to compile the shaders
  13981. * @param context defines the webGL context to use (if not set, the current one will be used)
  13982. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13983. * @returns the new webGL program
  13984. */
  13985. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13986. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13987. context = context || this._gl;
  13988. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13989. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13990. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13991. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13992. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13993. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13994. return program;
  13995. };
  13996. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13997. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13998. var shaderProgram = context.createProgram();
  13999. if (!shaderProgram) {
  14000. throw new Error("Unable to create program");
  14001. }
  14002. context.attachShader(shaderProgram, vertexShader);
  14003. context.attachShader(shaderProgram, fragmentShader);
  14004. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14005. var transformFeedback = this.createTransformFeedback();
  14006. this.bindTransformFeedback(transformFeedback);
  14007. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14008. shaderProgram.transformFeedback = transformFeedback;
  14009. }
  14010. context.linkProgram(shaderProgram);
  14011. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14012. this.bindTransformFeedback(null);
  14013. }
  14014. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14015. if (!linked) {
  14016. context.validateProgram(shaderProgram);
  14017. var error = context.getProgramInfoLog(shaderProgram);
  14018. if (error) {
  14019. throw new Error(error);
  14020. }
  14021. }
  14022. context.deleteShader(vertexShader);
  14023. context.deleteShader(fragmentShader);
  14024. return shaderProgram;
  14025. };
  14026. /**
  14027. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14028. * @param shaderProgram defines the webGL program to use
  14029. * @param uniformsNames defines the list of uniform names
  14030. * @returns an array of webGL uniform locations
  14031. */
  14032. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14033. var results = new Array();
  14034. for (var index = 0; index < uniformsNames.length; index++) {
  14035. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14036. }
  14037. return results;
  14038. };
  14039. /**
  14040. * Gets the lsit of active attributes for a given webGL program
  14041. * @param shaderProgram defines the webGL program to use
  14042. * @param attributesNames defines the list of attribute names to get
  14043. * @returns an array of indices indicating the offset of each attribute
  14044. */
  14045. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14046. var results = [];
  14047. for (var index = 0; index < attributesNames.length; index++) {
  14048. try {
  14049. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14050. }
  14051. catch (e) {
  14052. results.push(-1);
  14053. }
  14054. }
  14055. return results;
  14056. };
  14057. /**
  14058. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14059. * @param effect defines the effect to activate
  14060. */
  14061. Engine.prototype.enableEffect = function (effect) {
  14062. if (!effect) {
  14063. return;
  14064. }
  14065. // Use program
  14066. this.bindSamplers(effect);
  14067. this._currentEffect = effect;
  14068. if (effect.onBind) {
  14069. effect.onBind(effect);
  14070. }
  14071. effect.onBindObservable.notifyObservers(effect);
  14072. };
  14073. /**
  14074. * Set the value of an uniform to an array of int32
  14075. * @param uniform defines the webGL uniform location where to store the value
  14076. * @param array defines the array of int32 to store
  14077. */
  14078. Engine.prototype.setIntArray = function (uniform, array) {
  14079. if (!uniform)
  14080. return;
  14081. this._gl.uniform1iv(uniform, array);
  14082. };
  14083. /**
  14084. * Set the value of an uniform to an array of int32 (stored as vec2)
  14085. * @param uniform defines the webGL uniform location where to store the value
  14086. * @param array defines the array of int32 to store
  14087. */
  14088. Engine.prototype.setIntArray2 = function (uniform, array) {
  14089. if (!uniform || array.length % 2 !== 0)
  14090. return;
  14091. this._gl.uniform2iv(uniform, array);
  14092. };
  14093. /**
  14094. * Set the value of an uniform to an array of int32 (stored as vec3)
  14095. * @param uniform defines the webGL uniform location where to store the value
  14096. * @param array defines the array of int32 to store
  14097. */
  14098. Engine.prototype.setIntArray3 = function (uniform, array) {
  14099. if (!uniform || array.length % 3 !== 0)
  14100. return;
  14101. this._gl.uniform3iv(uniform, array);
  14102. };
  14103. /**
  14104. * Set the value of an uniform to an array of int32 (stored as vec4)
  14105. * @param uniform defines the webGL uniform location where to store the value
  14106. * @param array defines the array of int32 to store
  14107. */
  14108. Engine.prototype.setIntArray4 = function (uniform, array) {
  14109. if (!uniform || array.length % 4 !== 0)
  14110. return;
  14111. this._gl.uniform4iv(uniform, array);
  14112. };
  14113. /**
  14114. * Set the value of an uniform to an array of float32
  14115. * @param uniform defines the webGL uniform location where to store the value
  14116. * @param array defines the array of float32 to store
  14117. */
  14118. Engine.prototype.setFloatArray = function (uniform, array) {
  14119. if (!uniform)
  14120. return;
  14121. this._gl.uniform1fv(uniform, array);
  14122. };
  14123. /**
  14124. * Set the value of an uniform to an array of float32 (stored as vec2)
  14125. * @param uniform defines the webGL uniform location where to store the value
  14126. * @param array defines the array of float32 to store
  14127. */
  14128. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14129. if (!uniform || array.length % 2 !== 0)
  14130. return;
  14131. this._gl.uniform2fv(uniform, array);
  14132. };
  14133. /**
  14134. * Set the value of an uniform to an array of float32 (stored as vec3)
  14135. * @param uniform defines the webGL uniform location where to store the value
  14136. * @param array defines the array of float32 to store
  14137. */
  14138. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14139. if (!uniform || array.length % 3 !== 0)
  14140. return;
  14141. this._gl.uniform3fv(uniform, array);
  14142. };
  14143. /**
  14144. * Set the value of an uniform to an array of float32 (stored as vec4)
  14145. * @param uniform defines the webGL uniform location where to store the value
  14146. * @param array defines the array of float32 to store
  14147. */
  14148. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14149. if (!uniform || array.length % 4 !== 0)
  14150. return;
  14151. this._gl.uniform4fv(uniform, array);
  14152. };
  14153. /**
  14154. * Set the value of an uniform to an array of number
  14155. * @param uniform defines the webGL uniform location where to store the value
  14156. * @param array defines the array of number to store
  14157. */
  14158. Engine.prototype.setArray = function (uniform, array) {
  14159. if (!uniform)
  14160. return;
  14161. this._gl.uniform1fv(uniform, array);
  14162. };
  14163. /**
  14164. * Set the value of an uniform to an array of number (stored as vec2)
  14165. * @param uniform defines the webGL uniform location where to store the value
  14166. * @param array defines the array of number to store
  14167. */
  14168. Engine.prototype.setArray2 = function (uniform, array) {
  14169. if (!uniform || array.length % 2 !== 0)
  14170. return;
  14171. this._gl.uniform2fv(uniform, array);
  14172. };
  14173. /**
  14174. * Set the value of an uniform to an array of number (stored as vec3)
  14175. * @param uniform defines the webGL uniform location where to store the value
  14176. * @param array defines the array of number to store
  14177. */
  14178. Engine.prototype.setArray3 = function (uniform, array) {
  14179. if (!uniform || array.length % 3 !== 0)
  14180. return;
  14181. this._gl.uniform3fv(uniform, array);
  14182. };
  14183. /**
  14184. * Set the value of an uniform to an array of number (stored as vec4)
  14185. * @param uniform defines the webGL uniform location where to store the value
  14186. * @param array defines the array of number to store
  14187. */
  14188. Engine.prototype.setArray4 = function (uniform, array) {
  14189. if (!uniform || array.length % 4 !== 0)
  14190. return;
  14191. this._gl.uniform4fv(uniform, array);
  14192. };
  14193. /**
  14194. * Set the value of an uniform to an array of float32 (stored as matrices)
  14195. * @param uniform defines the webGL uniform location where to store the value
  14196. * @param matrices defines the array of float32 to store
  14197. */
  14198. Engine.prototype.setMatrices = function (uniform, matrices) {
  14199. if (!uniform)
  14200. return;
  14201. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14202. };
  14203. /**
  14204. * Set the value of an uniform to a matrix
  14205. * @param uniform defines the webGL uniform location where to store the value
  14206. * @param matrix defines the matrix to store
  14207. */
  14208. Engine.prototype.setMatrix = function (uniform, matrix) {
  14209. if (!uniform)
  14210. return;
  14211. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14212. };
  14213. /**
  14214. * Set the value of an uniform to a matrix (3x3)
  14215. * @param uniform defines the webGL uniform location where to store the value
  14216. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14217. */
  14218. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14219. if (!uniform)
  14220. return;
  14221. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14222. };
  14223. /**
  14224. * Set the value of an uniform to a matrix (2x2)
  14225. * @param uniform defines the webGL uniform location where to store the value
  14226. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14227. */
  14228. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14229. if (!uniform)
  14230. return;
  14231. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14232. };
  14233. /**
  14234. * Set the value of an uniform to a number (int)
  14235. * @param uniform defines the webGL uniform location where to store the value
  14236. * @param value defines the int number to store
  14237. */
  14238. Engine.prototype.setInt = function (uniform, value) {
  14239. if (!uniform)
  14240. return;
  14241. this._gl.uniform1i(uniform, value);
  14242. };
  14243. /**
  14244. * Set the value of an uniform to a number (float)
  14245. * @param uniform defines the webGL uniform location where to store the value
  14246. * @param value defines the float number to store
  14247. */
  14248. Engine.prototype.setFloat = function (uniform, value) {
  14249. if (!uniform)
  14250. return;
  14251. this._gl.uniform1f(uniform, value);
  14252. };
  14253. /**
  14254. * Set the value of an uniform to a vec2
  14255. * @param uniform defines the webGL uniform location where to store the value
  14256. * @param x defines the 1st component of the value
  14257. * @param y defines the 2nd component of the value
  14258. */
  14259. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14260. if (!uniform)
  14261. return;
  14262. this._gl.uniform2f(uniform, x, y);
  14263. };
  14264. /**
  14265. * Set the value of an uniform to a vec3
  14266. * @param uniform defines the webGL uniform location where to store the value
  14267. * @param x defines the 1st component of the value
  14268. * @param y defines the 2nd component of the value
  14269. * @param z defines the 3rd component of the value
  14270. */
  14271. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14272. if (!uniform)
  14273. return;
  14274. this._gl.uniform3f(uniform, x, y, z);
  14275. };
  14276. /**
  14277. * Set the value of an uniform to a boolean
  14278. * @param uniform defines the webGL uniform location where to store the value
  14279. * @param bool defines the boolean to store
  14280. */
  14281. Engine.prototype.setBool = function (uniform, bool) {
  14282. if (!uniform)
  14283. return;
  14284. this._gl.uniform1i(uniform, bool);
  14285. };
  14286. /**
  14287. * Set the value of an uniform to a vec4
  14288. * @param uniform defines the webGL uniform location where to store the value
  14289. * @param x defines the 1st component of the value
  14290. * @param y defines the 2nd component of the value
  14291. * @param z defines the 3rd component of the value
  14292. * @param w defines the 4th component of the value
  14293. */
  14294. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14295. if (!uniform)
  14296. return;
  14297. this._gl.uniform4f(uniform, x, y, z, w);
  14298. };
  14299. /**
  14300. * Set the value of an uniform to a Color3
  14301. * @param uniform defines the webGL uniform location where to store the value
  14302. * @param color3 defines the color to store
  14303. */
  14304. Engine.prototype.setColor3 = function (uniform, color3) {
  14305. if (!uniform)
  14306. return;
  14307. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14308. };
  14309. /**
  14310. * Set the value of an uniform to a Color3 and an alpha value
  14311. * @param uniform defines the webGL uniform location where to store the value
  14312. * @param color3 defines the color to store
  14313. * @param alpha defines the alpha component to store
  14314. */
  14315. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14316. if (!uniform)
  14317. return;
  14318. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14319. };
  14320. /**
  14321. * Sets a Color4 on a uniform variable
  14322. * @param uniform defines the uniform location
  14323. * @param color4 defines the value to be set
  14324. */
  14325. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14326. if (!uniform)
  14327. return;
  14328. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14329. };
  14330. // States
  14331. /**
  14332. * Set various states to the webGL context
  14333. * @param culling defines backface culling state
  14334. * @param zOffset defines the value to apply to zOffset (0 by default)
  14335. * @param force defines if states must be applied even if cache is up to date
  14336. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14337. */
  14338. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14339. if (zOffset === void 0) { zOffset = 0; }
  14340. if (reverseSide === void 0) { reverseSide = false; }
  14341. // Culling
  14342. if (this._depthCullingState.cull !== culling || force) {
  14343. this._depthCullingState.cull = culling;
  14344. }
  14345. // Cull face
  14346. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14347. if (this._depthCullingState.cullFace !== cullFace || force) {
  14348. this._depthCullingState.cullFace = cullFace;
  14349. }
  14350. // Z offset
  14351. this.setZOffset(zOffset);
  14352. // Front face
  14353. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14354. if (this._depthCullingState.frontFace !== frontFace || force) {
  14355. this._depthCullingState.frontFace = frontFace;
  14356. }
  14357. };
  14358. /**
  14359. * Set the z offset to apply to current rendering
  14360. * @param value defines the offset to apply
  14361. */
  14362. Engine.prototype.setZOffset = function (value) {
  14363. this._depthCullingState.zOffset = value;
  14364. };
  14365. /**
  14366. * Gets the current value of the zOffset
  14367. * @returns the current zOffset state
  14368. */
  14369. Engine.prototype.getZOffset = function () {
  14370. return this._depthCullingState.zOffset;
  14371. };
  14372. /**
  14373. * Enable or disable depth buffering
  14374. * @param enable defines the state to set
  14375. */
  14376. Engine.prototype.setDepthBuffer = function (enable) {
  14377. this._depthCullingState.depthTest = enable;
  14378. };
  14379. /**
  14380. * Gets a boolean indicating if depth writing is enabled
  14381. * @returns the current depth writing state
  14382. */
  14383. Engine.prototype.getDepthWrite = function () {
  14384. return this._depthCullingState.depthMask;
  14385. };
  14386. /**
  14387. * Enable or disable depth writing
  14388. * @param enable defines the state to set
  14389. */
  14390. Engine.prototype.setDepthWrite = function (enable) {
  14391. this._depthCullingState.depthMask = enable;
  14392. };
  14393. /**
  14394. * Enable or disable color writing
  14395. * @param enable defines the state to set
  14396. */
  14397. Engine.prototype.setColorWrite = function (enable) {
  14398. this._gl.colorMask(enable, enable, enable, enable);
  14399. this._colorWrite = enable;
  14400. };
  14401. /**
  14402. * Gets a boolean indicating if color writing is enabled
  14403. * @returns the current color writing state
  14404. */
  14405. Engine.prototype.getColorWrite = function () {
  14406. return this._colorWrite;
  14407. };
  14408. /**
  14409. * Sets alpha constants used by some alpha blending modes
  14410. * @param r defines the red component
  14411. * @param g defines the green component
  14412. * @param b defines the blue component
  14413. * @param a defines the alpha component
  14414. */
  14415. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14416. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14417. };
  14418. /**
  14419. * Sets the current alpha mode
  14420. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14421. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14422. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14423. */
  14424. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14425. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14426. if (this._alphaMode === mode) {
  14427. return;
  14428. }
  14429. switch (mode) {
  14430. case Engine.ALPHA_DISABLE:
  14431. this._alphaState.alphaBlend = false;
  14432. break;
  14433. case Engine.ALPHA_PREMULTIPLIED:
  14434. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14435. this._alphaState.alphaBlend = true;
  14436. break;
  14437. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14438. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14439. this._alphaState.alphaBlend = true;
  14440. break;
  14441. case Engine.ALPHA_COMBINE:
  14442. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14443. this._alphaState.alphaBlend = true;
  14444. break;
  14445. case Engine.ALPHA_ONEONE:
  14446. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14447. this._alphaState.alphaBlend = true;
  14448. break;
  14449. case Engine.ALPHA_ADD:
  14450. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14451. this._alphaState.alphaBlend = true;
  14452. break;
  14453. case Engine.ALPHA_SUBTRACT:
  14454. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14455. this._alphaState.alphaBlend = true;
  14456. break;
  14457. case Engine.ALPHA_MULTIPLY:
  14458. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14459. this._alphaState.alphaBlend = true;
  14460. break;
  14461. case Engine.ALPHA_MAXIMIZED:
  14462. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14463. this._alphaState.alphaBlend = true;
  14464. break;
  14465. case Engine.ALPHA_INTERPOLATE:
  14466. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14467. this._alphaState.alphaBlend = true;
  14468. break;
  14469. case Engine.ALPHA_SCREENMODE:
  14470. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14471. this._alphaState.alphaBlend = true;
  14472. break;
  14473. }
  14474. if (!noDepthWriteChange) {
  14475. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14476. }
  14477. this._alphaMode = mode;
  14478. };
  14479. /**
  14480. * Gets the current alpha mode
  14481. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14482. * @returns the current alpha mode
  14483. */
  14484. Engine.prototype.getAlphaMode = function () {
  14485. return this._alphaMode;
  14486. };
  14487. // Textures
  14488. /**
  14489. * Clears the list of texture accessible through engine.
  14490. * This can help preventing texture load conflict due to name collision.
  14491. */
  14492. Engine.prototype.clearInternalTexturesCache = function () {
  14493. this._internalTexturesCache = [];
  14494. };
  14495. /**
  14496. * Force the entire cache to be cleared
  14497. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14498. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14499. */
  14500. Engine.prototype.wipeCaches = function (bruteForce) {
  14501. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14502. return;
  14503. }
  14504. this._currentEffect = null;
  14505. if (bruteForce) {
  14506. this.resetTextureCache();
  14507. this._currentProgram = null;
  14508. this._stencilState.reset();
  14509. this._depthCullingState.reset();
  14510. this.setDepthFunctionToLessOrEqual();
  14511. this._alphaState.reset();
  14512. }
  14513. this._resetVertexBufferBinding();
  14514. this._cachedIndexBuffer = null;
  14515. this._cachedEffectForVertexBuffers = null;
  14516. this._unbindVertexArrayObject();
  14517. this.bindIndexBuffer(null);
  14518. };
  14519. /**
  14520. * Set the compressed texture format to use, based on the formats you have, and the formats
  14521. * supported by the hardware / browser.
  14522. *
  14523. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14524. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14525. * to API arguments needed to compressed textures. This puts the burden on the container
  14526. * generator to house the arcane code for determining these for current & future formats.
  14527. *
  14528. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14529. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14530. *
  14531. * Note: The result of this call is not taken into account when a texture is base64.
  14532. *
  14533. * @param formatsAvailable defines the list of those format families you have created
  14534. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14535. *
  14536. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14537. * @returns The extension selected.
  14538. */
  14539. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14540. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14541. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14542. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14543. return this._textureFormatInUse = this._texturesSupported[i];
  14544. }
  14545. }
  14546. }
  14547. // actively set format to nothing, to allow this to be called more than once
  14548. // and possibly fail the 2nd time
  14549. this._textureFormatInUse = null;
  14550. return null;
  14551. };
  14552. /** @hidden */
  14553. Engine.prototype._createTexture = function () {
  14554. var texture = this._gl.createTexture();
  14555. if (!texture) {
  14556. throw new Error("Unable to create texture");
  14557. }
  14558. return texture;
  14559. };
  14560. /**
  14561. * Usually called from BABYLON.Texture.ts.
  14562. * Passed information to create a WebGLTexture
  14563. * @param urlArg defines a value which contains one of the following:
  14564. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14565. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14566. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14567. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14568. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14569. * @param scene needed for loading to the correct scene
  14570. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14571. * @param onLoad optional callback to be called upon successful completion
  14572. * @param onError optional callback to be called upon failure
  14573. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14574. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14575. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14576. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14577. */
  14578. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14579. var _this = this;
  14580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14581. if (onLoad === void 0) { onLoad = null; }
  14582. if (onError === void 0) { onError = null; }
  14583. if (buffer === void 0) { buffer = null; }
  14584. if (fallback === void 0) { fallback = null; }
  14585. if (format === void 0) { format = null; }
  14586. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14587. var fromData = url.substr(0, 5) === "data:";
  14588. var fromBlob = url.substr(0, 5) === "blob:";
  14589. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14590. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14591. // establish the file extension, if possible
  14592. var lastDot = url.lastIndexOf('.');
  14593. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14594. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14595. var isTGA = (extension.indexOf(".tga") === 0);
  14596. // determine if a ktx file should be substituted
  14597. var isKTX = false;
  14598. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14599. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14600. isKTX = true;
  14601. }
  14602. if (scene) {
  14603. scene._addPendingData(texture);
  14604. }
  14605. texture.url = url;
  14606. texture.generateMipMaps = !noMipmap;
  14607. texture.samplingMode = samplingMode;
  14608. texture.invertY = invertY;
  14609. if (!this._doNotHandleContextLost) {
  14610. // Keep a link to the buffer only if we plan to handle context lost
  14611. texture._buffer = buffer;
  14612. }
  14613. var onLoadObserver = null;
  14614. if (onLoad && !fallback) {
  14615. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14616. }
  14617. if (!fallback)
  14618. this._internalTexturesCache.push(texture);
  14619. var onerror = function (message, exception) {
  14620. if (scene) {
  14621. scene._removePendingData(texture);
  14622. }
  14623. if (onLoadObserver) {
  14624. texture.onLoadedObservable.remove(onLoadObserver);
  14625. }
  14626. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14627. if (isKTX) {
  14628. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14629. }
  14630. else if (BABYLON.Tools.UseFallbackTexture) {
  14631. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14632. }
  14633. if (onError) {
  14634. onError(message || "Unknown error", exception);
  14635. }
  14636. };
  14637. var callback = null;
  14638. // processing for non-image formats
  14639. if (isKTX || isTGA || isDDS) {
  14640. if (isKTX) {
  14641. callback = function (data) {
  14642. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14643. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14644. ktx.uploadLevels(_this._gl, !noMipmap);
  14645. return false;
  14646. }, samplingMode);
  14647. };
  14648. }
  14649. else if (isTGA) {
  14650. callback = function (arrayBuffer) {
  14651. var data = new Uint8Array(arrayBuffer);
  14652. var header = BABYLON.TGATools.GetTGAHeader(data);
  14653. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14654. BABYLON.TGATools.UploadContent(_this._gl, data);
  14655. return false;
  14656. }, samplingMode);
  14657. };
  14658. }
  14659. else if (isDDS) {
  14660. callback = function (data) {
  14661. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14662. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14663. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14664. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14665. return false;
  14666. }, samplingMode);
  14667. };
  14668. }
  14669. if (!buffer) {
  14670. this._loadFile(url, function (data) {
  14671. if (callback) {
  14672. callback(data);
  14673. }
  14674. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14675. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14676. });
  14677. }
  14678. else {
  14679. if (callback) {
  14680. callback(buffer);
  14681. }
  14682. }
  14683. // image format processing
  14684. }
  14685. else {
  14686. var onload = function (img) {
  14687. if (fromBlob && !_this._doNotHandleContextLost) {
  14688. // We need to store the image if we need to rebuild the texture
  14689. // in case of a webgl context lost
  14690. texture._buffer = img;
  14691. }
  14692. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14693. var gl = _this._gl;
  14694. var isPot = (img.width === potWidth && img.height === potHeight);
  14695. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14696. if (isPot) {
  14697. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14698. return false;
  14699. }
  14700. // Using shaders to rescale because canvas.drawImage is lossy
  14701. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14702. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14703. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14704. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14705. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14706. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14707. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14708. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14709. _this._releaseTexture(source);
  14710. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14711. continuationCallback();
  14712. });
  14713. return true;
  14714. }, samplingMode);
  14715. };
  14716. if (!fromData || isBase64) {
  14717. if (buffer instanceof HTMLImageElement) {
  14718. onload(buffer);
  14719. }
  14720. else {
  14721. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14722. }
  14723. }
  14724. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14725. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14726. }
  14727. else {
  14728. onload(buffer);
  14729. }
  14730. }
  14731. return texture;
  14732. };
  14733. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14734. var _this = this;
  14735. var rtt = this.createRenderTargetTexture({
  14736. width: destination.width,
  14737. height: destination.height,
  14738. }, {
  14739. generateMipMaps: false,
  14740. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14741. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14742. generateDepthBuffer: false,
  14743. generateStencilBuffer: false
  14744. });
  14745. if (!this._rescalePostProcess) {
  14746. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14747. }
  14748. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14749. _this._rescalePostProcess.onApply = function (effect) {
  14750. effect._bindTexture("textureSampler", source);
  14751. };
  14752. var hostingScene = scene;
  14753. if (!hostingScene) {
  14754. hostingScene = _this.scenes[_this.scenes.length - 1];
  14755. }
  14756. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14757. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14758. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14759. _this.unBindFramebuffer(rtt);
  14760. _this._releaseTexture(rtt);
  14761. if (onComplete) {
  14762. onComplete();
  14763. }
  14764. });
  14765. };
  14766. /**
  14767. * Update a raw texture
  14768. * @param texture defines the texture to update
  14769. * @param data defines the data to store in the texture
  14770. * @param format defines the format of the data
  14771. * @param invertY defines if data must be stored with Y axis inverted
  14772. * @param compression defines the compression used (null by default)
  14773. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14774. */
  14775. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14776. if (compression === void 0) { compression = null; }
  14777. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14778. if (!texture) {
  14779. return;
  14780. }
  14781. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14782. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14783. // babylon's internalFormat but gl's texImage2D format
  14784. var internalFormat = this._getInternalFormat(format);
  14785. var textureType = this._getWebGLTextureType(type);
  14786. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14787. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14788. if (!this._doNotHandleContextLost) {
  14789. texture._bufferView = data;
  14790. texture.format = format;
  14791. texture.type = type;
  14792. texture.invertY = invertY;
  14793. texture._compression = compression;
  14794. }
  14795. if (texture.width % 4 !== 0) {
  14796. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14797. }
  14798. if (compression && data) {
  14799. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14800. }
  14801. else {
  14802. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14803. }
  14804. if (texture.generateMipMaps) {
  14805. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14806. }
  14807. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14808. // this.resetTextureCache();
  14809. texture.isReady = true;
  14810. };
  14811. /**
  14812. * Creates a raw texture
  14813. * @param data defines the data to store in the texture
  14814. * @param width defines the width of the texture
  14815. * @param height defines the height of the texture
  14816. * @param format defines the format of the data
  14817. * @param generateMipMaps defines if the engine should generate the mip levels
  14818. * @param invertY defines if data must be stored with Y axis inverted
  14819. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14820. * @param compression defines the compression used (null by default)
  14821. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14822. * @returns the raw texture inside an InternalTexture
  14823. */
  14824. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14825. if (compression === void 0) { compression = null; }
  14826. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14827. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14828. texture.baseWidth = width;
  14829. texture.baseHeight = height;
  14830. texture.width = width;
  14831. texture.height = height;
  14832. texture.format = format;
  14833. texture.generateMipMaps = generateMipMaps;
  14834. texture.samplingMode = samplingMode;
  14835. texture.invertY = invertY;
  14836. texture._compression = compression;
  14837. texture.type = type;
  14838. if (!this._doNotHandleContextLost) {
  14839. texture._bufferView = data;
  14840. }
  14841. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14842. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14843. // Filters
  14844. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14845. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14846. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14847. if (generateMipMaps) {
  14848. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14849. }
  14850. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14851. this._internalTexturesCache.push(texture);
  14852. return texture;
  14853. };
  14854. /**
  14855. * Creates a dynamic texture
  14856. * @param width defines the width of the texture
  14857. * @param height defines the height of the texture
  14858. * @param generateMipMaps defines if the engine should generate the mip levels
  14859. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14860. * @returns the dynamic texture inside an InternalTexture
  14861. */
  14862. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14863. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14864. texture.baseWidth = width;
  14865. texture.baseHeight = height;
  14866. if (generateMipMaps) {
  14867. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14868. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14869. }
  14870. // this.resetTextureCache();
  14871. texture.width = width;
  14872. texture.height = height;
  14873. texture.isReady = false;
  14874. texture.generateMipMaps = generateMipMaps;
  14875. texture.samplingMode = samplingMode;
  14876. this.updateTextureSamplingMode(samplingMode, texture);
  14877. this._internalTexturesCache.push(texture);
  14878. return texture;
  14879. };
  14880. /**
  14881. * Update the sampling mode of a given texture
  14882. * @param samplingMode defines the required sampling mode
  14883. * @param texture defines the texture to update
  14884. */
  14885. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14886. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14887. if (texture.isCube) {
  14888. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14889. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14890. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14891. }
  14892. else if (texture.is3D) {
  14893. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14894. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14895. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14896. }
  14897. else {
  14898. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14899. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14900. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14901. }
  14902. texture.samplingMode = samplingMode;
  14903. };
  14904. /**
  14905. * Update the content of a dynamic texture
  14906. * @param texture defines the texture to update
  14907. * @param canvas defines the canvas containing the source
  14908. * @param invertY defines if data must be stored with Y axis inverted
  14909. * @param premulAlpha defines if alpha is stored as premultiplied
  14910. * @param format defines the format of the data
  14911. */
  14912. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14913. if (premulAlpha === void 0) { premulAlpha = false; }
  14914. if (!texture) {
  14915. return;
  14916. }
  14917. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14918. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14919. if (premulAlpha) {
  14920. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14921. }
  14922. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14923. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14924. if (texture.generateMipMaps) {
  14925. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14926. }
  14927. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14928. if (premulAlpha) {
  14929. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14930. }
  14931. texture.isReady = true;
  14932. };
  14933. /**
  14934. * Update a video texture
  14935. * @param texture defines the texture to update
  14936. * @param video defines the video element to use
  14937. * @param invertY defines if data must be stored with Y axis inverted
  14938. */
  14939. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14940. if (!texture || texture._isDisabled) {
  14941. return;
  14942. }
  14943. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14944. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14945. try {
  14946. // Testing video texture support
  14947. if (this._videoTextureSupported === undefined) {
  14948. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14949. if (this._gl.getError() !== 0) {
  14950. this._videoTextureSupported = false;
  14951. }
  14952. else {
  14953. this._videoTextureSupported = true;
  14954. }
  14955. }
  14956. // Copy video through the current working canvas if video texture is not supported
  14957. if (!this._videoTextureSupported) {
  14958. if (!texture._workingCanvas) {
  14959. texture._workingCanvas = document.createElement("canvas");
  14960. var context = texture._workingCanvas.getContext("2d");
  14961. if (!context) {
  14962. throw new Error("Unable to get 2d context");
  14963. }
  14964. texture._workingContext = context;
  14965. texture._workingCanvas.width = texture.width;
  14966. texture._workingCanvas.height = texture.height;
  14967. }
  14968. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14969. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14970. }
  14971. else {
  14972. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14973. }
  14974. if (texture.generateMipMaps) {
  14975. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14976. }
  14977. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14978. // this.resetTextureCache();
  14979. texture.isReady = true;
  14980. }
  14981. catch (ex) {
  14982. // Something unexpected
  14983. // Let's disable the texture
  14984. texture._isDisabled = true;
  14985. }
  14986. };
  14987. /**
  14988. * Updates a depth texture Comparison Mode and Function.
  14989. * If the comparison Function is equal to 0, the mode will be set to none.
  14990. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14991. * @param texture The texture to set the comparison function for
  14992. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14993. */
  14994. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14995. if (this.webGLVersion === 1) {
  14996. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14997. return;
  14998. }
  14999. var gl = this._gl;
  15000. if (texture.isCube) {
  15001. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15002. if (comparisonFunction === 0) {
  15003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15004. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15005. }
  15006. else {
  15007. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15008. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15009. }
  15010. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15011. }
  15012. else {
  15013. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15014. if (comparisonFunction === 0) {
  15015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15017. }
  15018. else {
  15019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15021. }
  15022. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15023. }
  15024. texture._comparisonFunction = comparisonFunction;
  15025. };
  15026. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15027. var width = size.width || size;
  15028. var height = size.height || size;
  15029. internalTexture.baseWidth = width;
  15030. internalTexture.baseHeight = height;
  15031. internalTexture.width = width;
  15032. internalTexture.height = height;
  15033. internalTexture.isReady = true;
  15034. internalTexture.samples = 1;
  15035. internalTexture.generateMipMaps = false;
  15036. internalTexture._generateDepthBuffer = true;
  15037. internalTexture._generateStencilBuffer = generateStencil;
  15038. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15039. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15040. internalTexture._comparisonFunction = comparisonFunction;
  15041. var gl = this._gl;
  15042. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15043. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15044. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15045. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15046. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15047. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15048. if (comparisonFunction === 0) {
  15049. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15050. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15051. }
  15052. else {
  15053. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15054. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15055. }
  15056. };
  15057. /**
  15058. * Creates a depth stencil texture.
  15059. * This is only available in WebGL 2 or with the depth texture extension available.
  15060. * @param size The size of face edge in the texture.
  15061. * @param options The options defining the texture.
  15062. * @returns The texture
  15063. */
  15064. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15065. if (options.isCube) {
  15066. var width = size.width || size;
  15067. return this._createDepthStencilCubeTexture(width, options);
  15068. }
  15069. else {
  15070. return this._createDepthStencilTexture(size, options);
  15071. }
  15072. };
  15073. /**
  15074. * Creates a depth stencil texture.
  15075. * This is only available in WebGL 2 or with the depth texture extension available.
  15076. * @param size The size of face edge in the texture.
  15077. * @param options The options defining the texture.
  15078. * @returns The texture
  15079. */
  15080. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15081. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15082. if (!this._caps.depthTextureExtension) {
  15083. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15084. return internalTexture;
  15085. }
  15086. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15087. var gl = this._gl;
  15088. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15089. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15090. if (this.webGLVersion > 1) {
  15091. if (internalOptions.generateStencil) {
  15092. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15093. }
  15094. else {
  15095. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15096. }
  15097. }
  15098. else {
  15099. if (internalOptions.generateStencil) {
  15100. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15101. }
  15102. else {
  15103. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15104. }
  15105. }
  15106. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15107. return internalTexture;
  15108. };
  15109. /**
  15110. * Creates a depth stencil cube texture.
  15111. * This is only available in WebGL 2.
  15112. * @param size The size of face edge in the cube texture.
  15113. * @param options The options defining the cube texture.
  15114. * @returns The cube texture
  15115. */
  15116. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15117. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15118. internalTexture.isCube = true;
  15119. if (this.webGLVersion === 1) {
  15120. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15121. return internalTexture;
  15122. }
  15123. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15124. var gl = this._gl;
  15125. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15126. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15127. // Create the depth/stencil buffer
  15128. for (var face = 0; face < 6; face++) {
  15129. if (internalOptions.generateStencil) {
  15130. 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);
  15131. }
  15132. else {
  15133. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15134. }
  15135. }
  15136. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15137. return internalTexture;
  15138. };
  15139. /**
  15140. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15141. * @param renderTarget The render target to set the frame buffer for
  15142. */
  15143. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15144. // Create the framebuffer
  15145. var internalTexture = renderTarget.getInternalTexture();
  15146. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15147. return;
  15148. }
  15149. var gl = this._gl;
  15150. var depthStencilTexture = renderTarget.depthStencilTexture;
  15151. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15152. if (depthStencilTexture.isCube) {
  15153. if (depthStencilTexture._generateStencilBuffer) {
  15154. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15155. }
  15156. else {
  15157. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15158. }
  15159. }
  15160. else {
  15161. if (depthStencilTexture._generateStencilBuffer) {
  15162. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15163. }
  15164. else {
  15165. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15166. }
  15167. }
  15168. this.bindUnboundFramebuffer(null);
  15169. };
  15170. /**
  15171. * Creates a new render target texture
  15172. * @param size defines the size of the texture
  15173. * @param options defines the options used to create the texture
  15174. * @returns a new render target texture stored in an InternalTexture
  15175. */
  15176. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15177. var fullOptions = new RenderTargetCreationOptions();
  15178. if (options !== undefined && typeof options === "object") {
  15179. fullOptions.generateMipMaps = options.generateMipMaps;
  15180. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15181. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15182. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15183. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15184. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15185. }
  15186. else {
  15187. fullOptions.generateMipMaps = options;
  15188. fullOptions.generateDepthBuffer = true;
  15189. fullOptions.generateStencilBuffer = false;
  15190. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15191. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15192. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15193. }
  15194. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15195. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15196. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15197. }
  15198. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15199. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15200. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15201. }
  15202. var gl = this._gl;
  15203. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15204. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15205. var width = size.width || size;
  15206. var height = size.height || size;
  15207. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15208. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15209. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15210. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15211. }
  15212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15214. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15215. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15216. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15217. // Create the framebuffer
  15218. var currentFrameBuffer = this._currentFramebuffer;
  15219. var framebuffer = gl.createFramebuffer();
  15220. this.bindUnboundFramebuffer(framebuffer);
  15221. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15222. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15223. if (fullOptions.generateMipMaps) {
  15224. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15225. }
  15226. // Unbind
  15227. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15228. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15229. this.bindUnboundFramebuffer(currentFrameBuffer);
  15230. texture._framebuffer = framebuffer;
  15231. texture.baseWidth = width;
  15232. texture.baseHeight = height;
  15233. texture.width = width;
  15234. texture.height = height;
  15235. texture.isReady = true;
  15236. texture.samples = 1;
  15237. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15238. texture.samplingMode = fullOptions.samplingMode;
  15239. texture.type = fullOptions.type;
  15240. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15241. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15242. // this.resetTextureCache();
  15243. this._internalTexturesCache.push(texture);
  15244. return texture;
  15245. };
  15246. /**
  15247. * Create a multi render target texture
  15248. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15249. * @param size defines the size of the texture
  15250. * @param options defines the creation options
  15251. * @returns the cube texture as an InternalTexture
  15252. */
  15253. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15254. var generateMipMaps = false;
  15255. var generateDepthBuffer = true;
  15256. var generateStencilBuffer = false;
  15257. var generateDepthTexture = false;
  15258. var textureCount = 1;
  15259. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15260. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15261. var types = new Array();
  15262. var samplingModes = new Array();
  15263. if (options !== undefined) {
  15264. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15265. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15266. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15267. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15268. textureCount = options.textureCount || 1;
  15269. if (options.types) {
  15270. types = options.types;
  15271. }
  15272. if (options.samplingModes) {
  15273. samplingModes = options.samplingModes;
  15274. }
  15275. }
  15276. var gl = this._gl;
  15277. // Create the framebuffer
  15278. var framebuffer = gl.createFramebuffer();
  15279. this.bindUnboundFramebuffer(framebuffer);
  15280. var width = size.width || size;
  15281. var height = size.height || size;
  15282. var textures = [];
  15283. var attachments = [];
  15284. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15285. for (var i = 0; i < textureCount; i++) {
  15286. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15287. var type = types[i] || defaultType;
  15288. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15289. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15290. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15291. }
  15292. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15293. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15294. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15295. }
  15296. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15297. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15298. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15299. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15300. }
  15301. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15302. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15303. textures.push(texture);
  15304. attachments.push(attachment);
  15305. gl.activeTexture(gl["TEXTURE" + i]);
  15306. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15308. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15310. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15311. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15312. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15313. if (generateMipMaps) {
  15314. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15315. }
  15316. // Unbind
  15317. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15318. texture._framebuffer = framebuffer;
  15319. texture._depthStencilBuffer = depthStencilBuffer;
  15320. texture.baseWidth = width;
  15321. texture.baseHeight = height;
  15322. texture.width = width;
  15323. texture.height = height;
  15324. texture.isReady = true;
  15325. texture.samples = 1;
  15326. texture.generateMipMaps = generateMipMaps;
  15327. texture.samplingMode = samplingMode;
  15328. texture.type = type;
  15329. texture._generateDepthBuffer = generateDepthBuffer;
  15330. texture._generateStencilBuffer = generateStencilBuffer;
  15331. texture._attachments = attachments;
  15332. this._internalTexturesCache.push(texture);
  15333. }
  15334. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15335. // Depth texture
  15336. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15337. gl.activeTexture(gl.TEXTURE0);
  15338. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15340. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15341. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15342. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15343. 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);
  15344. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15345. depthTexture._framebuffer = framebuffer;
  15346. depthTexture.baseWidth = width;
  15347. depthTexture.baseHeight = height;
  15348. depthTexture.width = width;
  15349. depthTexture.height = height;
  15350. depthTexture.isReady = true;
  15351. depthTexture.samples = 1;
  15352. depthTexture.generateMipMaps = generateMipMaps;
  15353. depthTexture.samplingMode = gl.NEAREST;
  15354. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15355. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15356. textures.push(depthTexture);
  15357. this._internalTexturesCache.push(depthTexture);
  15358. }
  15359. gl.drawBuffers(attachments);
  15360. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15361. this.bindUnboundFramebuffer(null);
  15362. this.resetTextureCache();
  15363. return textures;
  15364. };
  15365. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15366. if (samples === void 0) { samples = 1; }
  15367. var depthStencilBuffer = null;
  15368. var gl = this._gl;
  15369. // Create the depth/stencil buffer
  15370. if (generateStencilBuffer) {
  15371. depthStencilBuffer = gl.createRenderbuffer();
  15372. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15373. if (samples > 1) {
  15374. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15375. }
  15376. else {
  15377. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15378. }
  15379. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15380. }
  15381. else if (generateDepthBuffer) {
  15382. depthStencilBuffer = gl.createRenderbuffer();
  15383. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15384. if (samples > 1) {
  15385. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15386. }
  15387. else {
  15388. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15389. }
  15390. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15391. }
  15392. return depthStencilBuffer;
  15393. };
  15394. /**
  15395. * Updates the sample count of a render target texture
  15396. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15397. * @param texture defines the texture to update
  15398. * @param samples defines the sample count to set
  15399. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15400. */
  15401. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15402. if (this.webGLVersion < 2 || !texture) {
  15403. return 1;
  15404. }
  15405. if (texture.samples === samples) {
  15406. return samples;
  15407. }
  15408. var gl = this._gl;
  15409. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15410. // Dispose previous render buffers
  15411. if (texture._depthStencilBuffer) {
  15412. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15413. texture._depthStencilBuffer = null;
  15414. }
  15415. if (texture._MSAAFramebuffer) {
  15416. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15417. texture._MSAAFramebuffer = null;
  15418. }
  15419. if (texture._MSAARenderBuffer) {
  15420. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15421. texture._MSAARenderBuffer = null;
  15422. }
  15423. if (samples > 1) {
  15424. var framebuffer = gl.createFramebuffer();
  15425. if (!framebuffer) {
  15426. throw new Error("Unable to create multi sampled framebuffer");
  15427. }
  15428. texture._MSAAFramebuffer = framebuffer;
  15429. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15430. var colorRenderbuffer = gl.createRenderbuffer();
  15431. if (!colorRenderbuffer) {
  15432. throw new Error("Unable to create multi sampled framebuffer");
  15433. }
  15434. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15435. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15436. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15437. texture._MSAARenderBuffer = colorRenderbuffer;
  15438. }
  15439. else {
  15440. this.bindUnboundFramebuffer(texture._framebuffer);
  15441. }
  15442. texture.samples = samples;
  15443. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15444. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15445. this.bindUnboundFramebuffer(null);
  15446. return samples;
  15447. };
  15448. /**
  15449. * Update the sample count for a given multiple render target texture
  15450. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15451. * @param textures defines the textures to update
  15452. * @param samples defines the sample count to set
  15453. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15454. */
  15455. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15456. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15457. return 1;
  15458. }
  15459. if (textures[0].samples === samples) {
  15460. return samples;
  15461. }
  15462. var gl = this._gl;
  15463. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15464. // Dispose previous render buffers
  15465. if (textures[0]._depthStencilBuffer) {
  15466. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15467. textures[0]._depthStencilBuffer = null;
  15468. }
  15469. if (textures[0]._MSAAFramebuffer) {
  15470. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15471. textures[0]._MSAAFramebuffer = null;
  15472. }
  15473. for (var i = 0; i < textures.length; i++) {
  15474. if (textures[i]._MSAARenderBuffer) {
  15475. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15476. textures[i]._MSAARenderBuffer = null;
  15477. }
  15478. }
  15479. if (samples > 1) {
  15480. var framebuffer = gl.createFramebuffer();
  15481. if (!framebuffer) {
  15482. throw new Error("Unable to create multi sampled framebuffer");
  15483. }
  15484. this.bindUnboundFramebuffer(framebuffer);
  15485. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15486. var attachments = [];
  15487. for (var i = 0; i < textures.length; i++) {
  15488. var texture = textures[i];
  15489. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15490. var colorRenderbuffer = gl.createRenderbuffer();
  15491. if (!colorRenderbuffer) {
  15492. throw new Error("Unable to create multi sampled framebuffer");
  15493. }
  15494. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15495. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15496. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15497. texture._MSAAFramebuffer = framebuffer;
  15498. texture._MSAARenderBuffer = colorRenderbuffer;
  15499. texture.samples = samples;
  15500. texture._depthStencilBuffer = depthStencilBuffer;
  15501. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15502. attachments.push(attachment);
  15503. }
  15504. gl.drawBuffers(attachments);
  15505. }
  15506. else {
  15507. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15508. }
  15509. this.bindUnboundFramebuffer(null);
  15510. return samples;
  15511. };
  15512. /** @hidden */
  15513. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15514. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15515. };
  15516. /** @hidden */
  15517. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15518. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15519. };
  15520. /** @hidden */
  15521. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15522. var gl = this._gl;
  15523. var textureType = this._getWebGLTextureType(texture.type);
  15524. var format = this._getInternalFormat(texture.format);
  15525. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15526. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15527. this._bindTextureDirectly(bindTarget, texture, true);
  15528. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.invertY ? 1 : 0);
  15529. var target = gl.TEXTURE_2D;
  15530. if (texture.isCube) {
  15531. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15532. }
  15533. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15534. this._bindTextureDirectly(bindTarget, null, true);
  15535. };
  15536. /**
  15537. * Creates a new render target cube texture
  15538. * @param size defines the size of the texture
  15539. * @param options defines the options used to create the texture
  15540. * @returns a new render target cube texture stored in an InternalTexture
  15541. */
  15542. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15543. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15544. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15545. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15546. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15547. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15548. }
  15549. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15550. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15551. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15552. }
  15553. var gl = this._gl;
  15554. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15555. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15556. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15557. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15558. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15559. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15560. }
  15561. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15562. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15563. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15564. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15565. for (var face = 0; face < 6; face++) {
  15566. 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);
  15567. }
  15568. // Create the framebuffer
  15569. var framebuffer = gl.createFramebuffer();
  15570. this.bindUnboundFramebuffer(framebuffer);
  15571. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15572. // MipMaps
  15573. if (fullOptions.generateMipMaps) {
  15574. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15575. }
  15576. // Unbind
  15577. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15578. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15579. this.bindUnboundFramebuffer(null);
  15580. texture._framebuffer = framebuffer;
  15581. texture.width = size;
  15582. texture.height = size;
  15583. texture.isReady = true;
  15584. texture.isCube = true;
  15585. texture.samples = 1;
  15586. texture.generateMipMaps = fullOptions.generateMipMaps;
  15587. texture.samplingMode = fullOptions.samplingMode;
  15588. texture.type = fullOptions.type;
  15589. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15590. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15591. this._internalTexturesCache.push(texture);
  15592. return texture;
  15593. };
  15594. /**
  15595. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15596. * @param rootUrl defines the url where the file to load is located
  15597. * @param scene defines the current scene
  15598. * @param lodScale defines scale to apply to the mip map selection
  15599. * @param lodOffset defines offset to apply to the mip map selection
  15600. * @param onLoad defines an optional callback raised when the texture is loaded
  15601. * @param onError defines an optional callback raised if there is an issue to load the texture
  15602. * @param format defines the format of the data
  15603. * @param forcedExtension defines the extension to use to pick the right loader
  15604. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15605. * @returns the cube texture as an InternalTexture
  15606. */
  15607. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15608. var _this = this;
  15609. if (onLoad === void 0) { onLoad = null; }
  15610. if (onError === void 0) { onError = null; }
  15611. if (forcedExtension === void 0) { forcedExtension = null; }
  15612. if (createPolynomials === void 0) { createPolynomials = true; }
  15613. var callback = function (loadData) {
  15614. if (!loadData) {
  15615. if (onLoad) {
  15616. onLoad(null);
  15617. }
  15618. return;
  15619. }
  15620. var texture = loadData.texture;
  15621. if (!createPolynomials) {
  15622. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15623. }
  15624. else if (loadData.info.sphericalPolynomial) {
  15625. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15626. }
  15627. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15628. if (_this._caps.textureLOD) {
  15629. // Do not add extra process if texture lod is supported.
  15630. if (onLoad) {
  15631. onLoad(texture);
  15632. }
  15633. return;
  15634. }
  15635. var mipSlices = 3;
  15636. var gl = _this._gl;
  15637. var width = loadData.width;
  15638. if (!width) {
  15639. return;
  15640. }
  15641. var textures = [];
  15642. for (var i = 0; i < mipSlices; i++) {
  15643. //compute LOD from even spacing in smoothness (matching shader calculation)
  15644. var smoothness = i / (mipSlices - 1);
  15645. var roughness = 1 - smoothness;
  15646. var minLODIndex = lodOffset; // roughness = 0
  15647. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15648. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15649. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15650. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15651. glTextureFromLod.isCube = true;
  15652. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15656. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15657. if (loadData.isDDS) {
  15658. var info = loadData.info;
  15659. var data = loadData.data;
  15660. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15661. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15662. }
  15663. else {
  15664. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15665. }
  15666. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15667. // Wrap in a base texture for easy binding.
  15668. var lodTexture = new BABYLON.BaseTexture(scene);
  15669. lodTexture.isCube = true;
  15670. lodTexture._texture = glTextureFromLod;
  15671. glTextureFromLod.isReady = true;
  15672. textures.push(lodTexture);
  15673. }
  15674. texture._lodTextureHigh = textures[2];
  15675. texture._lodTextureMid = textures[1];
  15676. texture._lodTextureLow = textures[0];
  15677. if (onLoad) {
  15678. onLoad(texture);
  15679. }
  15680. };
  15681. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15682. };
  15683. /**
  15684. * Creates a cube texture
  15685. * @param rootUrl defines the url where the files to load is located
  15686. * @param scene defines the current scene
  15687. * @param files defines the list of files to load (1 per face)
  15688. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15689. * @param onLoad defines an optional callback raised when the texture is loaded
  15690. * @param onError defines an optional callback raised if there is an issue to load the texture
  15691. * @param format defines the format of the data
  15692. * @param forcedExtension defines the extension to use to pick the right loader
  15693. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15694. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15695. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15696. * @returns the cube texture as an InternalTexture
  15697. */
  15698. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15699. var _this = this;
  15700. if (onLoad === void 0) { onLoad = null; }
  15701. if (onError === void 0) { onError = null; }
  15702. if (forcedExtension === void 0) { forcedExtension = null; }
  15703. if (createPolynomials === void 0) { createPolynomials = false; }
  15704. if (lodScale === void 0) { lodScale = 0; }
  15705. if (lodOffset === void 0) { lodOffset = 0; }
  15706. var gl = this._gl;
  15707. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15708. texture.isCube = true;
  15709. texture.url = rootUrl;
  15710. texture.generateMipMaps = !noMipmap;
  15711. texture._lodGenerationScale = lodScale;
  15712. texture._lodGenerationOffset = lodOffset;
  15713. if (!this._doNotHandleContextLost) {
  15714. texture._extension = forcedExtension;
  15715. texture._files = files;
  15716. }
  15717. var isKTX = false;
  15718. var isDDS = false;
  15719. var isEnv = false;
  15720. var lastDot = rootUrl.lastIndexOf('.');
  15721. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15722. if (this._textureFormatInUse) {
  15723. extension = this._textureFormatInUse;
  15724. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15725. isKTX = true;
  15726. }
  15727. else {
  15728. isDDS = (extension === ".dds");
  15729. isEnv = (extension === ".env");
  15730. }
  15731. var onerror = function (request, exception) {
  15732. if (onError && request) {
  15733. onError(request.status + " " + request.statusText, exception);
  15734. }
  15735. };
  15736. if (isKTX) {
  15737. this._loadFile(rootUrl, function (data) {
  15738. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15739. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15740. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15741. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15742. ktx.uploadLevels(_this._gl, !noMipmap);
  15743. _this.setCubeMapTextureParams(gl, loadMipmap);
  15744. texture.width = ktx.pixelWidth;
  15745. texture.height = ktx.pixelHeight;
  15746. texture.isReady = true;
  15747. }, undefined, undefined, true, onerror);
  15748. }
  15749. else if (isEnv) {
  15750. this._loadFile(rootUrl, function (data) {
  15751. data = data;
  15752. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15753. if (info) {
  15754. texture.width = info.width;
  15755. texture.height = info.width;
  15756. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15757. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15758. texture.isReady = true;
  15759. if (onLoad) {
  15760. onLoad();
  15761. }
  15762. });
  15763. }
  15764. else if (onError) {
  15765. onError("Can not parse the environment file", null);
  15766. }
  15767. }, undefined, undefined, true, onerror);
  15768. }
  15769. else if (isDDS) {
  15770. if (files && files.length === 6) {
  15771. this._cascadeLoadFiles(scene, function (imgs) {
  15772. var info;
  15773. var loadMipmap = false;
  15774. var width = 0;
  15775. for (var index = 0; index < imgs.length; index++) {
  15776. var data = imgs[index];
  15777. info = BABYLON.DDSTools.GetDDSInfo(data);
  15778. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15779. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15780. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15781. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15782. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15783. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15784. }
  15785. texture.width = info.width;
  15786. texture.height = info.height;
  15787. texture.type = info.textureType;
  15788. width = info.width;
  15789. }
  15790. _this.setCubeMapTextureParams(gl, loadMipmap);
  15791. texture.isReady = true;
  15792. if (onLoad) {
  15793. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15794. }
  15795. }, files, onError);
  15796. }
  15797. else {
  15798. this._loadFile(rootUrl, function (data) {
  15799. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15800. if (createPolynomials) {
  15801. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15802. }
  15803. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15804. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15805. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15806. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15807. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15808. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15809. }
  15810. _this.setCubeMapTextureParams(gl, loadMipmap);
  15811. texture.width = info.width;
  15812. texture.height = info.height;
  15813. texture.isReady = true;
  15814. texture.type = info.textureType;
  15815. if (onLoad) {
  15816. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15817. }
  15818. }, undefined, undefined, true, onerror);
  15819. }
  15820. }
  15821. else {
  15822. if (!files) {
  15823. throw new Error("Cannot load cubemap because files were not defined");
  15824. }
  15825. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15826. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15827. var height = width;
  15828. _this._prepareWorkingCanvas();
  15829. if (!_this._workingCanvas || !_this._workingContext) {
  15830. return;
  15831. }
  15832. _this._workingCanvas.width = width;
  15833. _this._workingCanvas.height = height;
  15834. var faces = [
  15835. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15836. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15837. ];
  15838. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15839. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15840. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15841. for (var index = 0; index < faces.length; index++) {
  15842. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15843. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15844. }
  15845. if (!noMipmap) {
  15846. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15847. }
  15848. _this.setCubeMapTextureParams(gl, !noMipmap);
  15849. texture.width = width;
  15850. texture.height = height;
  15851. texture.isReady = true;
  15852. if (format) {
  15853. texture.format = format;
  15854. }
  15855. texture.onLoadedObservable.notifyObservers(texture);
  15856. texture.onLoadedObservable.clear();
  15857. if (onLoad) {
  15858. onLoad();
  15859. }
  15860. }, files, onError);
  15861. }
  15862. this._internalTexturesCache.push(texture);
  15863. return texture;
  15864. };
  15865. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15866. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15867. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15868. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15869. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15870. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15871. // this.resetTextureCache();
  15872. };
  15873. /**
  15874. * Update a raw cube texture
  15875. * @param texture defines the texture to udpdate
  15876. * @param data defines the data to store
  15877. * @param format defines the data format
  15878. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15879. * @param invertY defines if data must be stored with Y axis inverted
  15880. * @param compression defines the compression used (null by default)
  15881. * @param level defines which level of the texture to update
  15882. */
  15883. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15884. if (compression === void 0) { compression = null; }
  15885. if (level === void 0) { level = 0; }
  15886. texture._bufferViewArray = data;
  15887. texture.format = format;
  15888. texture.type = type;
  15889. texture.invertY = invertY;
  15890. texture._compression = compression;
  15891. var gl = this._gl;
  15892. var textureType = this._getWebGLTextureType(type);
  15893. var internalFormat = this._getInternalFormat(format);
  15894. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15895. var needConversion = false;
  15896. if (internalFormat === gl.RGB) {
  15897. internalFormat = gl.RGBA;
  15898. needConversion = true;
  15899. }
  15900. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15901. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15902. if (texture.width % 4 !== 0) {
  15903. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15904. }
  15905. // Data are known to be in +X +Y +Z -X -Y -Z
  15906. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15907. var faceData = data[faceIndex];
  15908. if (compression) {
  15909. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15910. }
  15911. else {
  15912. if (needConversion) {
  15913. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15914. }
  15915. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15916. }
  15917. }
  15918. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15919. if (isPot && texture.generateMipMaps && level === 0) {
  15920. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15921. }
  15922. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15923. // this.resetTextureCache();
  15924. texture.isReady = true;
  15925. };
  15926. /**
  15927. * Creates a new raw cube texture
  15928. * @param data defines the array of data to use to create each face
  15929. * @param size defines the size of the textures
  15930. * @param format defines the format of the data
  15931. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15932. * @param generateMipMaps defines if the engine should generate the mip levels
  15933. * @param invertY defines if data must be stored with Y axis inverted
  15934. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15935. * @param compression defines the compression used (null by default)
  15936. * @returns the cube texture as an InternalTexture
  15937. */
  15938. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15939. if (compression === void 0) { compression = null; }
  15940. var gl = this._gl;
  15941. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15942. texture.isCube = true;
  15943. texture.generateMipMaps = generateMipMaps;
  15944. texture.format = format;
  15945. texture.type = type;
  15946. if (!this._doNotHandleContextLost) {
  15947. texture._bufferViewArray = data;
  15948. }
  15949. var textureType = this._getWebGLTextureType(type);
  15950. var internalFormat = this._getInternalFormat(format);
  15951. if (internalFormat === gl.RGB) {
  15952. internalFormat = gl.RGBA;
  15953. }
  15954. var width = size;
  15955. var height = width;
  15956. texture.width = width;
  15957. texture.height = height;
  15958. // Double check on POT to generate Mips.
  15959. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15960. if (!isPot) {
  15961. generateMipMaps = false;
  15962. }
  15963. // Upload data if needed. The texture won't be ready until then.
  15964. if (data) {
  15965. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15966. }
  15967. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15968. // Filters
  15969. if (data && generateMipMaps) {
  15970. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15971. }
  15972. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15973. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15974. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15975. }
  15976. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15977. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15978. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15979. }
  15980. else {
  15981. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15982. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15983. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15984. }
  15985. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15986. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15987. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15988. return texture;
  15989. };
  15990. /**
  15991. * Creates a new raw cube texture from a specified url
  15992. * @param url defines the url where the data is located
  15993. * @param scene defines the current scene
  15994. * @param size defines the size of the textures
  15995. * @param format defines the format of the data
  15996. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15997. * @param noMipmap defines if the engine should avoid generating the mip levels
  15998. * @param callback defines a callback used to extract texture data from loaded data
  15999. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16000. * @param onLoad defines a callback called when texture is loaded
  16001. * @param onError defines a callback called if there is an error
  16002. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16003. * @param invertY defines if data must be stored with Y axis inverted
  16004. * @returns the cube texture as an InternalTexture
  16005. */
  16006. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16007. var _this = this;
  16008. if (onLoad === void 0) { onLoad = null; }
  16009. if (onError === void 0) { onError = null; }
  16010. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16011. if (invertY === void 0) { invertY = false; }
  16012. var gl = this._gl;
  16013. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16014. scene._addPendingData(texture);
  16015. texture.url = url;
  16016. this._internalTexturesCache.push(texture);
  16017. var onerror = function (request, exception) {
  16018. scene._removePendingData(texture);
  16019. if (onError && request) {
  16020. onError(request.status + " " + request.statusText, exception);
  16021. }
  16022. };
  16023. var internalCallback = function (data) {
  16024. var width = texture.width;
  16025. var faceDataArrays = callback(data);
  16026. if (!faceDataArrays) {
  16027. return;
  16028. }
  16029. if (mipmapGenerator) {
  16030. var textureType = _this._getWebGLTextureType(type);
  16031. var internalFormat = _this._getInternalFormat(format);
  16032. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16033. var needConversion = false;
  16034. if (internalFormat === gl.RGB) {
  16035. internalFormat = gl.RGBA;
  16036. needConversion = true;
  16037. }
  16038. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16039. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  16040. var mipData = mipmapGenerator(faceDataArrays);
  16041. for (var level = 0; level < mipData.length; level++) {
  16042. var mipSize = width >> level;
  16043. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16044. var mipFaceData = mipData[level][faceIndex];
  16045. if (needConversion) {
  16046. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16047. }
  16048. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16049. }
  16050. }
  16051. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16052. }
  16053. else {
  16054. texture.generateMipMaps = !noMipmap;
  16055. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16056. }
  16057. texture.isReady = true;
  16058. // this.resetTextureCache();
  16059. scene._removePendingData(texture);
  16060. if (onLoad) {
  16061. onLoad();
  16062. }
  16063. };
  16064. this._loadFile(url, function (data) {
  16065. internalCallback(data);
  16066. }, undefined, scene.database, true, onerror);
  16067. return texture;
  16068. };
  16069. ;
  16070. /**
  16071. * Update a raw 3D texture
  16072. * @param texture defines the texture to update
  16073. * @param data defines the data to store
  16074. * @param format defines the data format
  16075. * @param invertY defines if data must be stored with Y axis inverted
  16076. * @param compression defines the used compression (can be null)
  16077. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16078. */
  16079. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16080. if (compression === void 0) { compression = null; }
  16081. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16082. var internalType = this._getWebGLTextureType(textureType);
  16083. var internalFormat = this._getInternalFormat(format);
  16084. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16085. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16086. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16087. if (!this._doNotHandleContextLost) {
  16088. texture._bufferView = data;
  16089. texture.format = format;
  16090. texture.invertY = invertY;
  16091. texture._compression = compression;
  16092. }
  16093. if (texture.width % 4 !== 0) {
  16094. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16095. }
  16096. if (compression && data) {
  16097. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16098. }
  16099. else {
  16100. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16101. }
  16102. if (texture.generateMipMaps) {
  16103. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16104. }
  16105. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16106. // this.resetTextureCache();
  16107. texture.isReady = true;
  16108. };
  16109. /**
  16110. * Creates a new raw 3D texture
  16111. * @param data defines the data used to create the texture
  16112. * @param width defines the width of the texture
  16113. * @param height defines the height of the texture
  16114. * @param depth defines the depth of the texture
  16115. * @param format defines the format of the texture
  16116. * @param generateMipMaps defines if the engine must generate mip levels
  16117. * @param invertY defines if data must be stored with Y axis inverted
  16118. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16119. * @param compression defines the compressed used (can be null)
  16120. * @param textureType defines the compressed used (can be null)
  16121. * @returns a new raw 3D texture (stored in an InternalTexture)
  16122. */
  16123. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16124. if (compression === void 0) { compression = null; }
  16125. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16126. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16127. texture.baseWidth = width;
  16128. texture.baseHeight = height;
  16129. texture.baseDepth = depth;
  16130. texture.width = width;
  16131. texture.height = height;
  16132. texture.depth = depth;
  16133. texture.format = format;
  16134. texture.type = textureType;
  16135. texture.generateMipMaps = generateMipMaps;
  16136. texture.samplingMode = samplingMode;
  16137. texture.is3D = true;
  16138. if (!this._doNotHandleContextLost) {
  16139. texture._bufferView = data;
  16140. }
  16141. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16142. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16143. // Filters
  16144. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16145. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16146. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16147. if (generateMipMaps) {
  16148. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16149. }
  16150. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16151. this._internalTexturesCache.push(texture);
  16152. return texture;
  16153. };
  16154. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16155. var gl = this._gl;
  16156. if (!gl) {
  16157. return;
  16158. }
  16159. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16160. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16162. if (!noMipmap && !isCompressed) {
  16163. gl.generateMipmap(gl.TEXTURE_2D);
  16164. }
  16165. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16166. // this.resetTextureCache();
  16167. if (scene) {
  16168. scene._removePendingData(texture);
  16169. }
  16170. texture.onLoadedObservable.notifyObservers(texture);
  16171. texture.onLoadedObservable.clear();
  16172. };
  16173. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16174. var _this = this;
  16175. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16176. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16177. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16178. var gl = this._gl;
  16179. if (!gl) {
  16180. return;
  16181. }
  16182. if (!texture._webGLTexture) {
  16183. // this.resetTextureCache();
  16184. if (scene) {
  16185. scene._removePendingData(texture);
  16186. }
  16187. return;
  16188. }
  16189. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16190. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16191. texture.baseWidth = width;
  16192. texture.baseHeight = height;
  16193. texture.width = potWidth;
  16194. texture.height = potHeight;
  16195. texture.isReady = true;
  16196. if (processFunction(potWidth, potHeight, function () {
  16197. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16198. })) {
  16199. // Returning as texture needs extra async steps
  16200. return;
  16201. }
  16202. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16203. };
  16204. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16205. // Create new RGBA data container.
  16206. var rgbaData;
  16207. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16208. rgbaData = new Float32Array(width * height * 4);
  16209. }
  16210. else {
  16211. rgbaData = new Uint32Array(width * height * 4);
  16212. }
  16213. // Convert each pixel.
  16214. for (var x = 0; x < width; x++) {
  16215. for (var y = 0; y < height; y++) {
  16216. var index = (y * width + x) * 3;
  16217. var newIndex = (y * width + x) * 4;
  16218. // Map Old Value to new value.
  16219. rgbaData[newIndex + 0] = rgbData[index + 0];
  16220. rgbaData[newIndex + 1] = rgbData[index + 1];
  16221. rgbaData[newIndex + 2] = rgbData[index + 2];
  16222. // Add fully opaque alpha channel.
  16223. rgbaData[newIndex + 3] = 1;
  16224. }
  16225. }
  16226. return rgbaData;
  16227. };
  16228. /** @hidden */
  16229. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16230. var gl = this._gl;
  16231. if (texture._framebuffer) {
  16232. gl.deleteFramebuffer(texture._framebuffer);
  16233. texture._framebuffer = null;
  16234. }
  16235. if (texture._depthStencilBuffer) {
  16236. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16237. texture._depthStencilBuffer = null;
  16238. }
  16239. if (texture._MSAAFramebuffer) {
  16240. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16241. texture._MSAAFramebuffer = null;
  16242. }
  16243. if (texture._MSAARenderBuffer) {
  16244. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16245. texture._MSAARenderBuffer = null;
  16246. }
  16247. };
  16248. /** @hidden */
  16249. Engine.prototype._releaseTexture = function (texture) {
  16250. var gl = this._gl;
  16251. this._releaseFramebufferObjects(texture);
  16252. gl.deleteTexture(texture._webGLTexture);
  16253. // Unbind channels
  16254. this.unbindAllTextures();
  16255. var index = this._internalTexturesCache.indexOf(texture);
  16256. if (index !== -1) {
  16257. this._internalTexturesCache.splice(index, 1);
  16258. }
  16259. // Integrated fixed lod samplers.
  16260. if (texture._lodTextureHigh) {
  16261. texture._lodTextureHigh.dispose();
  16262. }
  16263. if (texture._lodTextureMid) {
  16264. texture._lodTextureMid.dispose();
  16265. }
  16266. if (texture._lodTextureLow) {
  16267. texture._lodTextureLow.dispose();
  16268. }
  16269. // Set output texture of post process to null if the texture has been released/disposed
  16270. this.scenes.forEach(function (scene) {
  16271. scene.postProcesses.forEach(function (postProcess) {
  16272. if (postProcess._outputTexture == texture) {
  16273. postProcess._outputTexture = null;
  16274. }
  16275. });
  16276. scene.cameras.forEach(function (camera) {
  16277. camera._postProcesses.forEach(function (postProcess) {
  16278. if (postProcess) {
  16279. if (postProcess._outputTexture == texture) {
  16280. postProcess._outputTexture = null;
  16281. }
  16282. }
  16283. });
  16284. });
  16285. });
  16286. };
  16287. Engine.prototype.setProgram = function (program) {
  16288. if (this._currentProgram !== program) {
  16289. this._gl.useProgram(program);
  16290. this._currentProgram = program;
  16291. }
  16292. };
  16293. /**
  16294. * Binds an effect to the webGL context
  16295. * @param effect defines the effect to bind
  16296. */
  16297. Engine.prototype.bindSamplers = function (effect) {
  16298. this.setProgram(effect.getProgram());
  16299. var samplers = effect.getSamplers();
  16300. for (var index = 0; index < samplers.length; index++) {
  16301. var uniform = effect.getUniform(samplers[index]);
  16302. if (uniform) {
  16303. this._boundUniforms[index] = uniform;
  16304. }
  16305. }
  16306. this._currentEffect = null;
  16307. };
  16308. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16309. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16310. return;
  16311. }
  16312. // Remove
  16313. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16314. // Bind last to it
  16315. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16316. // Bind to dummy
  16317. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16318. };
  16319. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16320. if (!internalTexture) {
  16321. return -1;
  16322. }
  16323. internalTexture._initialSlot = channel;
  16324. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16325. if (channel !== internalTexture._designatedSlot) {
  16326. this._textureCollisions.addCount(1, false);
  16327. }
  16328. }
  16329. else {
  16330. if (channel !== internalTexture._designatedSlot) {
  16331. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16332. return internalTexture._designatedSlot;
  16333. }
  16334. else {
  16335. // No slot for this texture, let's pick a new one (if we find a free slot)
  16336. if (this._nextFreeTextureSlots.length) {
  16337. return this._nextFreeTextureSlots[0];
  16338. }
  16339. // We need to recycle the oldest bound texture, sorry.
  16340. this._textureCollisions.addCount(1, false);
  16341. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16342. }
  16343. }
  16344. }
  16345. return channel;
  16346. };
  16347. Engine.prototype._linkTrackers = function (previous, next) {
  16348. previous.next = next;
  16349. next.previous = previous;
  16350. };
  16351. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16352. var currentSlot = internalTexture._designatedSlot;
  16353. if (currentSlot === -1) {
  16354. return -1;
  16355. }
  16356. internalTexture._designatedSlot = -1;
  16357. if (this.disableTextureBindingOptimization) {
  16358. return -1;
  16359. }
  16360. // Remove from bound list
  16361. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16362. // Free the slot
  16363. this._boundTexturesCache[currentSlot] = null;
  16364. this._nextFreeTextureSlots.push(currentSlot);
  16365. return currentSlot;
  16366. };
  16367. Engine.prototype._activateCurrentTexture = function () {
  16368. if (this._currentTextureChannel !== this._activeChannel) {
  16369. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16370. this._currentTextureChannel = this._activeChannel;
  16371. }
  16372. };
  16373. /** @hidden */
  16374. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16375. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16376. if (force === void 0) { force = false; }
  16377. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16378. this._activeChannel = texture._designatedSlot;
  16379. }
  16380. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16381. var isTextureForRendering = texture && texture._initialSlot > -1;
  16382. if (currentTextureBound !== texture || force) {
  16383. if (currentTextureBound) {
  16384. this._removeDesignatedSlot(currentTextureBound);
  16385. }
  16386. this._activateCurrentTexture();
  16387. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16388. this._boundTexturesCache[this._activeChannel] = texture;
  16389. if (texture) {
  16390. if (!this.disableTextureBindingOptimization) {
  16391. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16392. if (slotIndex > -1) {
  16393. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16394. }
  16395. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16396. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16397. }
  16398. texture._designatedSlot = this._activeChannel;
  16399. }
  16400. }
  16401. else if (forTextureDataUpdate) {
  16402. this._activateCurrentTexture();
  16403. }
  16404. if (isTextureForRendering && !forTextureDataUpdate) {
  16405. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16406. }
  16407. };
  16408. /** @hidden */
  16409. Engine.prototype._bindTexture = function (channel, texture) {
  16410. if (channel < 0) {
  16411. return;
  16412. }
  16413. if (texture) {
  16414. channel = this._getCorrectTextureChannel(channel, texture);
  16415. }
  16416. this._activeChannel = channel;
  16417. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16418. };
  16419. /**
  16420. * Sets a texture to the webGL context from a postprocess
  16421. * @param channel defines the channel to use
  16422. * @param postProcess defines the source postprocess
  16423. */
  16424. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16425. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16426. };
  16427. /**
  16428. * Binds the output of the passed in post process to the texture channel specified
  16429. * @param channel The channel the texture should be bound to
  16430. * @param postProcess The post process which's output should be bound
  16431. */
  16432. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16433. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16434. };
  16435. /**
  16436. * Unbind all textures from the webGL context
  16437. */
  16438. Engine.prototype.unbindAllTextures = function () {
  16439. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16440. this._activeChannel = channel;
  16441. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16442. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16443. if (this.webGLVersion > 1) {
  16444. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16445. }
  16446. }
  16447. };
  16448. /**
  16449. * Sets a texture to the according uniform.
  16450. * @param channel The texture channel
  16451. * @param uniform The uniform to set
  16452. * @param texture The texture to apply
  16453. */
  16454. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16455. if (channel < 0) {
  16456. return;
  16457. }
  16458. if (uniform) {
  16459. this._boundUniforms[channel] = uniform;
  16460. }
  16461. this._setTexture(channel, texture);
  16462. };
  16463. /**
  16464. * Sets a depth stencil texture from a render target to the according uniform.
  16465. * @param channel The texture channel
  16466. * @param uniform The uniform to set
  16467. * @param texture The render target texture containing the depth stencil texture to apply
  16468. */
  16469. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16470. if (channel < 0) {
  16471. return;
  16472. }
  16473. if (uniform) {
  16474. this._boundUniforms[channel] = uniform;
  16475. }
  16476. if (!texture || !texture.depthStencilTexture) {
  16477. this._setTexture(channel, null);
  16478. }
  16479. else {
  16480. this._setTexture(channel, texture, false, true);
  16481. }
  16482. };
  16483. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16484. var uniform = this._boundUniforms[sourceSlot];
  16485. if (uniform._currentState === destination) {
  16486. return;
  16487. }
  16488. this._gl.uniform1i(uniform, destination);
  16489. uniform._currentState = destination;
  16490. };
  16491. Engine.prototype._getTextureWrapMode = function (mode) {
  16492. switch (mode) {
  16493. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16494. return this._gl.REPEAT;
  16495. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16496. return this._gl.CLAMP_TO_EDGE;
  16497. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16498. return this._gl.MIRRORED_REPEAT;
  16499. }
  16500. return this._gl.REPEAT;
  16501. };
  16502. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16503. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16504. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16505. // Not ready?
  16506. if (!texture) {
  16507. if (this._boundTexturesCache[channel] != null) {
  16508. this._activeChannel = channel;
  16509. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16510. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16511. if (this.webGLVersion > 1) {
  16512. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16513. }
  16514. }
  16515. return false;
  16516. }
  16517. // Video
  16518. if (texture.video) {
  16519. this._activeChannel = channel;
  16520. texture.update();
  16521. }
  16522. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16523. texture.delayLoad();
  16524. return false;
  16525. }
  16526. var internalTexture;
  16527. if (depthStencilTexture) {
  16528. internalTexture = texture.depthStencilTexture;
  16529. }
  16530. else if (texture.isReady()) {
  16531. internalTexture = texture.getInternalTexture();
  16532. }
  16533. else if (texture.isCube) {
  16534. internalTexture = this.emptyCubeTexture;
  16535. }
  16536. else if (texture.is3D) {
  16537. internalTexture = this.emptyTexture3D;
  16538. }
  16539. else {
  16540. internalTexture = this.emptyTexture;
  16541. }
  16542. if (!isPartOfTextureArray) {
  16543. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16544. }
  16545. var needToBind = true;
  16546. if (this._boundTexturesCache[channel] === internalTexture) {
  16547. this._moveBoundTextureOnTop(internalTexture);
  16548. if (!isPartOfTextureArray) {
  16549. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16550. }
  16551. needToBind = false;
  16552. }
  16553. this._activeChannel = channel;
  16554. if (internalTexture && internalTexture.is3D) {
  16555. if (needToBind) {
  16556. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16557. }
  16558. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16559. internalTexture._cachedWrapU = texture.wrapU;
  16560. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16561. }
  16562. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16563. internalTexture._cachedWrapV = texture.wrapV;
  16564. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16565. }
  16566. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16567. internalTexture._cachedWrapR = texture.wrapR;
  16568. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16569. }
  16570. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16571. }
  16572. else if (internalTexture && internalTexture.isCube) {
  16573. if (needToBind) {
  16574. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16575. }
  16576. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16577. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16578. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16579. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16580. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16581. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16582. }
  16583. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16584. }
  16585. else {
  16586. if (needToBind) {
  16587. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16588. }
  16589. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16590. internalTexture._cachedWrapU = texture.wrapU;
  16591. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16592. }
  16593. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16594. internalTexture._cachedWrapV = texture.wrapV;
  16595. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16596. }
  16597. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16598. }
  16599. return true;
  16600. };
  16601. /**
  16602. * Sets an array of texture to the webGL context
  16603. * @param channel defines the channel where the texture array must be set
  16604. * @param uniform defines the associated uniform location
  16605. * @param textures defines the array of textures to bind
  16606. */
  16607. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16608. if (channel < 0 || !uniform) {
  16609. return;
  16610. }
  16611. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16612. this._textureUnits = new Int32Array(textures.length);
  16613. }
  16614. for (var i = 0; i < textures.length; i++) {
  16615. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16616. }
  16617. this._gl.uniform1iv(uniform, this._textureUnits);
  16618. for (var index = 0; index < textures.length; index++) {
  16619. this._setTexture(this._textureUnits[index], textures[index], true);
  16620. }
  16621. };
  16622. /** @hidden */
  16623. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16624. var internalTexture = texture.getInternalTexture();
  16625. if (!internalTexture) {
  16626. return;
  16627. }
  16628. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16629. var value = texture.anisotropicFilteringLevel;
  16630. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16631. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16632. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16633. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16634. }
  16635. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16636. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16637. internalTexture._cachedAnisotropicFilteringLevel = value;
  16638. }
  16639. };
  16640. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16641. this._bindTextureDirectly(target, texture, true, true);
  16642. this._gl.texParameterf(target, parameter, value);
  16643. };
  16644. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16645. if (texture) {
  16646. this._bindTextureDirectly(target, texture, true, true);
  16647. }
  16648. this._gl.texParameteri(target, parameter, value);
  16649. };
  16650. /**
  16651. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16652. * @param x defines the x coordinate of the rectangle where pixels must be read
  16653. * @param y defines the y coordinate of the rectangle where pixels must be read
  16654. * @param width defines the width of the rectangle where pixels must be read
  16655. * @param height defines the height of the rectangle where pixels must be read
  16656. * @returns a Uint8Array containing RGBA colors
  16657. */
  16658. Engine.prototype.readPixels = function (x, y, width, height) {
  16659. var data = new Uint8Array(height * width * 4);
  16660. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16661. return data;
  16662. };
  16663. /**
  16664. * Add an externaly attached data from its key.
  16665. * This method call will fail and return false, if such key already exists.
  16666. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16667. * @param key the unique key that identifies the data
  16668. * @param data the data object to associate to the key for this Engine instance
  16669. * @return true if no such key were already present and the data was added successfully, false otherwise
  16670. */
  16671. Engine.prototype.addExternalData = function (key, data) {
  16672. if (!this._externalData) {
  16673. this._externalData = new BABYLON.StringDictionary();
  16674. }
  16675. return this._externalData.add(key, data);
  16676. };
  16677. /**
  16678. * Get an externaly attached data from its key
  16679. * @param key the unique key that identifies the data
  16680. * @return the associated data, if present (can be null), or undefined if not present
  16681. */
  16682. Engine.prototype.getExternalData = function (key) {
  16683. if (!this._externalData) {
  16684. this._externalData = new BABYLON.StringDictionary();
  16685. }
  16686. return this._externalData.get(key);
  16687. };
  16688. /**
  16689. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16690. * @param key the unique key that identifies the data
  16691. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16692. * @return the associated data, can be null if the factory returned null.
  16693. */
  16694. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16695. if (!this._externalData) {
  16696. this._externalData = new BABYLON.StringDictionary();
  16697. }
  16698. return this._externalData.getOrAddWithFactory(key, factory);
  16699. };
  16700. /**
  16701. * Remove an externaly attached data from the Engine instance
  16702. * @param key the unique key that identifies the data
  16703. * @return true if the data was successfully removed, false if it doesn't exist
  16704. */
  16705. Engine.prototype.removeExternalData = function (key) {
  16706. if (!this._externalData) {
  16707. this._externalData = new BABYLON.StringDictionary();
  16708. }
  16709. return this._externalData.remove(key);
  16710. };
  16711. /**
  16712. * Unbind all vertex attributes from the webGL context
  16713. */
  16714. Engine.prototype.unbindAllAttributes = function () {
  16715. if (this._mustWipeVertexAttributes) {
  16716. this._mustWipeVertexAttributes = false;
  16717. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16718. this._gl.disableVertexAttribArray(i);
  16719. this._vertexAttribArraysEnabled[i] = false;
  16720. this._currentBufferPointers[i].active = false;
  16721. }
  16722. return;
  16723. }
  16724. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16725. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16726. continue;
  16727. }
  16728. this._gl.disableVertexAttribArray(i);
  16729. this._vertexAttribArraysEnabled[i] = false;
  16730. this._currentBufferPointers[i].active = false;
  16731. }
  16732. };
  16733. /**
  16734. * 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
  16735. */
  16736. Engine.prototype.releaseEffects = function () {
  16737. for (var name in this._compiledEffects) {
  16738. this._deleteProgram(this._compiledEffects[name]._program);
  16739. }
  16740. this._compiledEffects = {};
  16741. };
  16742. /**
  16743. * Dispose and release all associated resources
  16744. */
  16745. Engine.prototype.dispose = function () {
  16746. this.hideLoadingUI();
  16747. this.stopRenderLoop();
  16748. // Release postProcesses
  16749. while (this.postProcesses.length) {
  16750. this.postProcesses[0].dispose();
  16751. }
  16752. // Empty texture
  16753. if (this._emptyTexture) {
  16754. this._releaseTexture(this._emptyTexture);
  16755. this._emptyTexture = null;
  16756. }
  16757. if (this._emptyCubeTexture) {
  16758. this._releaseTexture(this._emptyCubeTexture);
  16759. this._emptyCubeTexture = null;
  16760. }
  16761. // Rescale PP
  16762. if (this._rescalePostProcess) {
  16763. this._rescalePostProcess.dispose();
  16764. }
  16765. // Release scenes
  16766. while (this.scenes.length) {
  16767. this.scenes[0].dispose();
  16768. }
  16769. // Release audio engine
  16770. if (Engine.audioEngine) {
  16771. Engine.audioEngine.dispose();
  16772. }
  16773. // Release effects
  16774. this.releaseEffects();
  16775. // Unbind
  16776. this.unbindAllAttributes();
  16777. this._boundUniforms = [];
  16778. if (this._dummyFramebuffer) {
  16779. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16780. }
  16781. //WebVR
  16782. this.disableVR();
  16783. // Events
  16784. if (BABYLON.Tools.IsWindowObjectExist()) {
  16785. window.removeEventListener("blur", this._onBlur);
  16786. window.removeEventListener("focus", this._onFocus);
  16787. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16788. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16789. if (this._renderingCanvas) {
  16790. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16791. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16792. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16793. if (!this._doNotHandleContextLost) {
  16794. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16795. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16796. }
  16797. }
  16798. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16799. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16800. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16801. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16802. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16803. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16804. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16805. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16806. if (this._onVrDisplayConnect) {
  16807. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16808. if (this._onVrDisplayDisconnect) {
  16809. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16810. }
  16811. if (this._onVrDisplayPresentChange) {
  16812. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16813. }
  16814. this._onVrDisplayConnect = null;
  16815. this._onVrDisplayDisconnect = null;
  16816. }
  16817. }
  16818. // Remove from Instances
  16819. var index = Engine.Instances.indexOf(this);
  16820. if (index >= 0) {
  16821. Engine.Instances.splice(index, 1);
  16822. }
  16823. this._workingCanvas = null;
  16824. this._workingContext = null;
  16825. this._currentBufferPointers = [];
  16826. this._renderingCanvas = null;
  16827. this._currentProgram = null;
  16828. this._bindedRenderFunction = null;
  16829. this.onResizeObservable.clear();
  16830. this.onCanvasBlurObservable.clear();
  16831. this.onCanvasFocusObservable.clear();
  16832. this.onCanvasPointerOutObservable.clear();
  16833. this.onBeginFrameObservable.clear();
  16834. this.onEndFrameObservable.clear();
  16835. BABYLON.Effect.ResetCache();
  16836. // Abort active requests
  16837. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16838. var request = _a[_i];
  16839. request.abort();
  16840. }
  16841. };
  16842. // Loading screen
  16843. /**
  16844. * Display the loading screen
  16845. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16846. */
  16847. Engine.prototype.displayLoadingUI = function () {
  16848. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16849. return;
  16850. }
  16851. var loadingScreen = this.loadingScreen;
  16852. if (loadingScreen) {
  16853. loadingScreen.displayLoadingUI();
  16854. }
  16855. };
  16856. /**
  16857. * Hide the loading screen
  16858. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16859. */
  16860. Engine.prototype.hideLoadingUI = function () {
  16861. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16862. return;
  16863. }
  16864. var loadingScreen = this.loadingScreen;
  16865. if (loadingScreen) {
  16866. loadingScreen.hideLoadingUI();
  16867. }
  16868. };
  16869. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16870. /**
  16871. * Gets the current loading screen object
  16872. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16873. */
  16874. get: function () {
  16875. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16876. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16877. return this._loadingScreen;
  16878. },
  16879. /**
  16880. * Sets the current loading screen object
  16881. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16882. */
  16883. set: function (loadingScreen) {
  16884. this._loadingScreen = loadingScreen;
  16885. },
  16886. enumerable: true,
  16887. configurable: true
  16888. });
  16889. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16890. /**
  16891. * Sets the current loading screen text
  16892. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16893. */
  16894. set: function (text) {
  16895. this.loadingScreen.loadingUIText = text;
  16896. },
  16897. enumerable: true,
  16898. configurable: true
  16899. });
  16900. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16901. /**
  16902. * Sets the current loading screen background color
  16903. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16904. */
  16905. set: function (color) {
  16906. this.loadingScreen.loadingUIBackgroundColor = color;
  16907. },
  16908. enumerable: true,
  16909. configurable: true
  16910. });
  16911. /**
  16912. * Attach a new callback raised when context lost event is fired
  16913. * @param callback defines the callback to call
  16914. */
  16915. Engine.prototype.attachContextLostEvent = function (callback) {
  16916. if (this._renderingCanvas) {
  16917. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16918. }
  16919. };
  16920. /**
  16921. * Attach a new callback raised when context restored event is fired
  16922. * @param callback defines the callback to call
  16923. */
  16924. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16925. if (this._renderingCanvas) {
  16926. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16927. }
  16928. };
  16929. /**
  16930. * Gets the source code of the vertex shader associated with a specific webGL program
  16931. * @param program defines the program to use
  16932. * @returns a string containing the source code of the vertex shader associated with the program
  16933. */
  16934. Engine.prototype.getVertexShaderSource = function (program) {
  16935. var shaders = this._gl.getAttachedShaders(program);
  16936. if (!shaders) {
  16937. return null;
  16938. }
  16939. return this._gl.getShaderSource(shaders[0]);
  16940. };
  16941. /**
  16942. * Gets the source code of the fragment shader associated with a specific webGL program
  16943. * @param program defines the program to use
  16944. * @returns a string containing the source code of the fragment shader associated with the program
  16945. */
  16946. Engine.prototype.getFragmentShaderSource = function (program) {
  16947. var shaders = this._gl.getAttachedShaders(program);
  16948. if (!shaders) {
  16949. return null;
  16950. }
  16951. return this._gl.getShaderSource(shaders[1]);
  16952. };
  16953. /**
  16954. * Get the current error code of the webGL context
  16955. * @returns the error code
  16956. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16957. */
  16958. Engine.prototype.getError = function () {
  16959. return this._gl.getError();
  16960. };
  16961. // FPS
  16962. /**
  16963. * Gets the current framerate
  16964. * @returns a number representing the framerate
  16965. */
  16966. Engine.prototype.getFps = function () {
  16967. return this._fps;
  16968. };
  16969. /**
  16970. * Gets the time spent between current and previous frame
  16971. * @returns a number representing the delta time in ms
  16972. */
  16973. Engine.prototype.getDeltaTime = function () {
  16974. return this._deltaTime;
  16975. };
  16976. Engine.prototype._measureFps = function () {
  16977. this._performanceMonitor.sampleFrame();
  16978. this._fps = this._performanceMonitor.averageFPS;
  16979. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16980. };
  16981. /** @hidden */
  16982. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16983. if (faceIndex === void 0) { faceIndex = -1; }
  16984. if (level === void 0) { level = 0; }
  16985. var gl = this._gl;
  16986. if (!this._dummyFramebuffer) {
  16987. var dummy = gl.createFramebuffer();
  16988. if (!dummy) {
  16989. throw new Error("Unable to create dummy framebuffer");
  16990. }
  16991. this._dummyFramebuffer = dummy;
  16992. }
  16993. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16994. if (faceIndex > -1) {
  16995. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16996. }
  16997. else {
  16998. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16999. }
  17000. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17001. var buffer;
  17002. switch (readType) {
  17003. case gl.UNSIGNED_BYTE:
  17004. buffer = new Uint8Array(4 * width * height);
  17005. readType = gl.UNSIGNED_BYTE;
  17006. break;
  17007. default:
  17008. buffer = new Float32Array(4 * width * height);
  17009. readType = gl.FLOAT;
  17010. break;
  17011. }
  17012. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17013. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17014. return buffer;
  17015. };
  17016. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17017. if (this._webGLVersion > 1) {
  17018. return this._caps.colorBufferFloat;
  17019. }
  17020. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17021. };
  17022. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17023. if (this._webGLVersion > 1) {
  17024. return this._caps.colorBufferFloat;
  17025. }
  17026. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17027. };
  17028. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17029. Engine.prototype._canRenderToFramebuffer = function (type) {
  17030. var gl = this._gl;
  17031. //clear existing errors
  17032. while (gl.getError() !== gl.NO_ERROR) { }
  17033. var successful = true;
  17034. var texture = gl.createTexture();
  17035. gl.bindTexture(gl.TEXTURE_2D, texture);
  17036. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17037. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17038. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17039. var fb = gl.createFramebuffer();
  17040. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17041. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17042. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17043. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17044. successful = successful && (gl.getError() === gl.NO_ERROR);
  17045. //try render by clearing frame buffer's color buffer
  17046. if (successful) {
  17047. gl.clear(gl.COLOR_BUFFER_BIT);
  17048. successful = successful && (gl.getError() === gl.NO_ERROR);
  17049. }
  17050. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17051. if (successful) {
  17052. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17053. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17054. var readFormat = gl.RGBA;
  17055. var readType = gl.UNSIGNED_BYTE;
  17056. var buffer = new Uint8Array(4);
  17057. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17058. successful = successful && (gl.getError() === gl.NO_ERROR);
  17059. }
  17060. //clean up
  17061. gl.deleteTexture(texture);
  17062. gl.deleteFramebuffer(fb);
  17063. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17064. //clear accumulated errors
  17065. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17066. return successful;
  17067. };
  17068. /** @hidden */
  17069. Engine.prototype._getWebGLTextureType = function (type) {
  17070. if (type === Engine.TEXTURETYPE_FLOAT) {
  17071. return this._gl.FLOAT;
  17072. }
  17073. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17074. // Add Half Float Constant.
  17075. return this._gl.HALF_FLOAT_OES;
  17076. }
  17077. return this._gl.UNSIGNED_BYTE;
  17078. };
  17079. ;
  17080. Engine.prototype._getInternalFormat = function (format) {
  17081. var internalFormat = this._gl.RGBA;
  17082. switch (format) {
  17083. case Engine.TEXTUREFORMAT_ALPHA:
  17084. internalFormat = this._gl.ALPHA;
  17085. break;
  17086. case Engine.TEXTUREFORMAT_LUMINANCE:
  17087. internalFormat = this._gl.LUMINANCE;
  17088. break;
  17089. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17090. internalFormat = this._gl.LUMINANCE_ALPHA;
  17091. break;
  17092. case Engine.TEXTUREFORMAT_RGB:
  17093. internalFormat = this._gl.RGB;
  17094. break;
  17095. case Engine.TEXTUREFORMAT_RGBA:
  17096. internalFormat = this._gl.RGBA;
  17097. break;
  17098. case Engine.TEXTUREFORMAT_R:
  17099. internalFormat = this._gl.RED;
  17100. break;
  17101. case Engine.TEXTUREFORMAT_RG:
  17102. internalFormat = this._gl.RG;
  17103. break;
  17104. }
  17105. return internalFormat;
  17106. };
  17107. /** @hidden */
  17108. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17109. if (this._webGLVersion === 1) {
  17110. if (format !== undefined) {
  17111. switch (format) {
  17112. case Engine.TEXTUREFORMAT_LUMINANCE:
  17113. return this._gl.LUMINANCE;
  17114. case Engine.TEXTUREFORMAT_ALPHA:
  17115. return this._gl.ALPHA;
  17116. }
  17117. }
  17118. return this._gl.RGBA;
  17119. }
  17120. if (type === Engine.TEXTURETYPE_FLOAT) {
  17121. if (format !== undefined) {
  17122. switch (format) {
  17123. case Engine.TEXTUREFORMAT_R:
  17124. return this._gl.R32F;
  17125. case Engine.TEXTUREFORMAT_RG:
  17126. return this._gl.RG32F;
  17127. case Engine.TEXTUREFORMAT_RGB:
  17128. return this._gl.RGB32F;
  17129. }
  17130. }
  17131. return this._gl.RGBA32F;
  17132. }
  17133. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17134. if (format) {
  17135. switch (format) {
  17136. case Engine.TEXTUREFORMAT_R:
  17137. return this._gl.R16F;
  17138. case Engine.TEXTUREFORMAT_RG:
  17139. return this._gl.RG16F;
  17140. case Engine.TEXTUREFORMAT_RGB:
  17141. return this._gl.RGB16F;
  17142. }
  17143. }
  17144. return this._gl.RGBA16F;
  17145. }
  17146. if (format !== undefined) {
  17147. switch (format) {
  17148. case Engine.TEXTUREFORMAT_LUMINANCE:
  17149. return this._gl.LUMINANCE;
  17150. case Engine.TEXTUREFORMAT_RGB:
  17151. return this._gl.RGB;
  17152. case Engine.TEXTUREFORMAT_R:
  17153. return this._gl.R8;
  17154. case Engine.TEXTUREFORMAT_RG:
  17155. return this._gl.RG8;
  17156. case Engine.TEXTUREFORMAT_ALPHA:
  17157. return this._gl.ALPHA;
  17158. }
  17159. }
  17160. return this._gl.RGBA;
  17161. };
  17162. ;
  17163. /** @hidden */
  17164. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17165. if (type === Engine.TEXTURETYPE_FLOAT) {
  17166. return this._gl.RGBA32F;
  17167. }
  17168. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17169. return this._gl.RGBA16F;
  17170. }
  17171. return this._gl.RGBA8;
  17172. };
  17173. ;
  17174. /**
  17175. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17176. * @return the new query
  17177. */
  17178. Engine.prototype.createQuery = function () {
  17179. return this._gl.createQuery();
  17180. };
  17181. /**
  17182. * Delete and release a webGL query
  17183. * @param query defines the query to delete
  17184. * @return the current engine
  17185. */
  17186. Engine.prototype.deleteQuery = function (query) {
  17187. this._gl.deleteQuery(query);
  17188. return this;
  17189. };
  17190. /**
  17191. * Check if a given query has resolved and got its value
  17192. * @param query defines the query to check
  17193. * @returns true if the query got its value
  17194. */
  17195. Engine.prototype.isQueryResultAvailable = function (query) {
  17196. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17197. };
  17198. /**
  17199. * Gets the value of a given query
  17200. * @param query defines the query to check
  17201. * @returns the value of the query
  17202. */
  17203. Engine.prototype.getQueryResult = function (query) {
  17204. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17205. };
  17206. /**
  17207. * Initiates an occlusion query
  17208. * @param algorithmType defines the algorithm to use
  17209. * @param query defines the query to use
  17210. * @returns the current engine
  17211. * @see http://doc.babylonjs.com/features/occlusionquery
  17212. */
  17213. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17214. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17215. this._gl.beginQuery(glAlgorithm, query);
  17216. return this;
  17217. };
  17218. /**
  17219. * Ends an occlusion query
  17220. * @see http://doc.babylonjs.com/features/occlusionquery
  17221. * @param algorithmType defines the algorithm to use
  17222. * @returns the current engine
  17223. */
  17224. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17225. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17226. this._gl.endQuery(glAlgorithm);
  17227. return this;
  17228. };
  17229. /* Time queries */
  17230. Engine.prototype._createTimeQuery = function () {
  17231. var timerQuery = this._caps.timerQuery;
  17232. if (timerQuery.createQueryEXT) {
  17233. return timerQuery.createQueryEXT();
  17234. }
  17235. return this.createQuery();
  17236. };
  17237. Engine.prototype._deleteTimeQuery = function (query) {
  17238. var timerQuery = this._caps.timerQuery;
  17239. if (timerQuery.deleteQueryEXT) {
  17240. timerQuery.deleteQueryEXT(query);
  17241. return;
  17242. }
  17243. this.deleteQuery(query);
  17244. };
  17245. Engine.prototype._getTimeQueryResult = function (query) {
  17246. var timerQuery = this._caps.timerQuery;
  17247. if (timerQuery.getQueryObjectEXT) {
  17248. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17249. }
  17250. return this.getQueryResult(query);
  17251. };
  17252. Engine.prototype._getTimeQueryAvailability = function (query) {
  17253. var timerQuery = this._caps.timerQuery;
  17254. if (timerQuery.getQueryObjectEXT) {
  17255. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17256. }
  17257. return this.isQueryResultAvailable(query);
  17258. };
  17259. /**
  17260. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17261. * Please note that only one query can be issued at a time
  17262. * @returns a time token used to track the time span
  17263. */
  17264. Engine.prototype.startTimeQuery = function () {
  17265. var timerQuery = this._caps.timerQuery;
  17266. if (!timerQuery) {
  17267. return null;
  17268. }
  17269. var token = new BABYLON._TimeToken();
  17270. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17271. if (this._caps.canUseTimestampForTimerQuery) {
  17272. token._startTimeQuery = this._createTimeQuery();
  17273. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17274. }
  17275. else {
  17276. if (this._currentNonTimestampToken) {
  17277. return this._currentNonTimestampToken;
  17278. }
  17279. token._timeElapsedQuery = this._createTimeQuery();
  17280. if (timerQuery.beginQueryEXT) {
  17281. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17282. }
  17283. else {
  17284. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17285. }
  17286. this._currentNonTimestampToken = token;
  17287. }
  17288. return token;
  17289. };
  17290. /**
  17291. * Ends a time query
  17292. * @param token defines the token used to measure the time span
  17293. * @returns the time spent (in ns)
  17294. */
  17295. Engine.prototype.endTimeQuery = function (token) {
  17296. var timerQuery = this._caps.timerQuery;
  17297. if (!timerQuery || !token) {
  17298. return -1;
  17299. }
  17300. if (this._caps.canUseTimestampForTimerQuery) {
  17301. if (!token._startTimeQuery) {
  17302. return -1;
  17303. }
  17304. if (!token._endTimeQuery) {
  17305. token._endTimeQuery = this._createTimeQuery();
  17306. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17307. }
  17308. }
  17309. else if (!token._timeElapsedQueryEnded) {
  17310. if (!token._timeElapsedQuery) {
  17311. return -1;
  17312. }
  17313. if (timerQuery.endQueryEXT) {
  17314. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17315. }
  17316. else {
  17317. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17318. }
  17319. token._timeElapsedQueryEnded = true;
  17320. }
  17321. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17322. var available = false;
  17323. if (token._endTimeQuery) {
  17324. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17325. }
  17326. else if (token._timeElapsedQuery) {
  17327. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17328. }
  17329. if (available && !disjoint) {
  17330. var result = 0;
  17331. if (this._caps.canUseTimestampForTimerQuery) {
  17332. if (!token._startTimeQuery || !token._endTimeQuery) {
  17333. return -1;
  17334. }
  17335. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17336. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17337. result = timeEnd - timeStart;
  17338. this._deleteTimeQuery(token._startTimeQuery);
  17339. this._deleteTimeQuery(token._endTimeQuery);
  17340. token._startTimeQuery = null;
  17341. token._endTimeQuery = null;
  17342. }
  17343. else {
  17344. if (!token._timeElapsedQuery) {
  17345. return -1;
  17346. }
  17347. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17348. this._deleteTimeQuery(token._timeElapsedQuery);
  17349. token._timeElapsedQuery = null;
  17350. token._timeElapsedQueryEnded = false;
  17351. this._currentNonTimestampToken = null;
  17352. }
  17353. return result;
  17354. }
  17355. return -1;
  17356. };
  17357. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17358. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17359. };
  17360. // Transform feedback
  17361. /**
  17362. * Creates a webGL transform feedback object
  17363. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17364. * @returns the webGL transform feedback object
  17365. */
  17366. Engine.prototype.createTransformFeedback = function () {
  17367. return this._gl.createTransformFeedback();
  17368. };
  17369. /**
  17370. * Delete a webGL transform feedback object
  17371. * @param value defines the webGL transform feedback object to delete
  17372. */
  17373. Engine.prototype.deleteTransformFeedback = function (value) {
  17374. this._gl.deleteTransformFeedback(value);
  17375. };
  17376. /**
  17377. * Bind a webGL transform feedback object to the webgl context
  17378. * @param value defines the webGL transform feedback object to bind
  17379. */
  17380. Engine.prototype.bindTransformFeedback = function (value) {
  17381. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17382. };
  17383. /**
  17384. * Begins a transform feedback operation
  17385. * @param usePoints defines if points or triangles must be used
  17386. */
  17387. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17388. if (usePoints === void 0) { usePoints = true; }
  17389. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17390. };
  17391. /**
  17392. * Ends a transform feedback operation
  17393. */
  17394. Engine.prototype.endTransformFeedback = function () {
  17395. this._gl.endTransformFeedback();
  17396. };
  17397. /**
  17398. * Specify the varyings to use with transform feedback
  17399. * @param program defines the associated webGL program
  17400. * @param value defines the list of strings representing the varying names
  17401. */
  17402. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17403. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17404. };
  17405. /**
  17406. * Bind a webGL buffer for a transform feedback operation
  17407. * @param value defines the webGL buffer to bind
  17408. */
  17409. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17410. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17411. };
  17412. /** @hidden */
  17413. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17414. var _this = this;
  17415. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17416. this._activeRequests.push(request);
  17417. request.onCompleteObservable.add(function (request) {
  17418. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17419. });
  17420. return request;
  17421. };
  17422. /** @hidden */
  17423. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17424. var _this = this;
  17425. return new Promise(function (resolve, reject) {
  17426. _this._loadFile(url, function (data) {
  17427. resolve(data);
  17428. }, undefined, database, useArrayBuffer, function (request, exception) {
  17429. reject(exception);
  17430. });
  17431. });
  17432. };
  17433. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17434. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17435. var onload = function (data) {
  17436. loadedFiles[index] = data;
  17437. loadedFiles._internalCount++;
  17438. if (loadedFiles._internalCount === 6) {
  17439. onfinish(loadedFiles);
  17440. }
  17441. };
  17442. var onerror = function (request, exception) {
  17443. if (onErrorCallBack && request) {
  17444. onErrorCallBack(request.status + " " + request.statusText, exception);
  17445. }
  17446. };
  17447. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17448. };
  17449. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17450. if (onError === void 0) { onError = null; }
  17451. var loadedFiles = [];
  17452. loadedFiles._internalCount = 0;
  17453. for (var index = 0; index < 6; index++) {
  17454. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17455. }
  17456. };
  17457. // Statics
  17458. /**
  17459. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17460. * @returns true if the engine can be created
  17461. * @ignorenaming
  17462. */
  17463. Engine.isSupported = function () {
  17464. try {
  17465. var tempcanvas = document.createElement("canvas");
  17466. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17467. return gl != null && !!window.WebGLRenderingContext;
  17468. }
  17469. catch (e) {
  17470. return false;
  17471. }
  17472. };
  17473. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17474. Engine.ExceptionList = [
  17475. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17476. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17477. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17478. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17479. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17480. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17481. ];
  17482. /** Gets the list of created engines */
  17483. Engine.Instances = new Array();
  17484. // Const statics
  17485. Engine._ALPHA_DISABLE = 0;
  17486. Engine._ALPHA_ADD = 1;
  17487. Engine._ALPHA_COMBINE = 2;
  17488. Engine._ALPHA_SUBTRACT = 3;
  17489. Engine._ALPHA_MULTIPLY = 4;
  17490. Engine._ALPHA_MAXIMIZED = 5;
  17491. Engine._ALPHA_ONEONE = 6;
  17492. Engine._ALPHA_PREMULTIPLIED = 7;
  17493. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17494. Engine._ALPHA_INTERPOLATE = 9;
  17495. Engine._ALPHA_SCREENMODE = 10;
  17496. Engine._DELAYLOADSTATE_NONE = 0;
  17497. Engine._DELAYLOADSTATE_LOADED = 1;
  17498. Engine._DELAYLOADSTATE_LOADING = 2;
  17499. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17500. Engine._TEXTUREFORMAT_ALPHA = 0;
  17501. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17502. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17503. Engine._TEXTUREFORMAT_RGB = 4;
  17504. Engine._TEXTUREFORMAT_RGBA = 5;
  17505. Engine._TEXTUREFORMAT_R = 6;
  17506. Engine._TEXTUREFORMAT_RG = 7;
  17507. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17508. Engine._TEXTURETYPE_FLOAT = 1;
  17509. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17510. // Depht or Stencil test Constants.
  17511. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17512. 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.
  17513. 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.
  17514. 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.
  17515. 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.
  17516. 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.
  17517. 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.
  17518. 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.
  17519. // Stencil Actions Constants.
  17520. Engine._KEEP = 0x1E00;
  17521. Engine._REPLACE = 0x1E01;
  17522. Engine._INCR = 0x1E02;
  17523. Engine._DECR = 0x1E03;
  17524. Engine._INVERT = 0x150A;
  17525. Engine._INCR_WRAP = 0x8507;
  17526. Engine._DECR_WRAP = 0x8508;
  17527. // Texture rescaling mode
  17528. Engine._SCALEMODE_FLOOR = 1;
  17529. Engine._SCALEMODE_NEAREST = 2;
  17530. Engine._SCALEMODE_CEILING = 3;
  17531. // Updatable statics so stick with vars here
  17532. /**
  17533. * Gets or sets the epsilon value used by collision engine
  17534. */
  17535. Engine.CollisionsEpsilon = 0.001;
  17536. /**
  17537. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17538. */
  17539. Engine.CodeRepository = "src/";
  17540. /**
  17541. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17542. */
  17543. Engine.ShadersRepository = "src/Shaders/";
  17544. return Engine;
  17545. }());
  17546. BABYLON.Engine = Engine;
  17547. })(BABYLON || (BABYLON = {}));
  17548. //# sourceMappingURL=babylon.engine.js.map
  17549. var BABYLON;
  17550. (function (BABYLON) {
  17551. /**
  17552. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17553. */
  17554. var Node = /** @class */ (function () {
  17555. /**
  17556. * Creates a new Node
  17557. * @param {string} name - the name and id to be given to this node
  17558. * @param {BABYLON.Scene} the scene this node will be added to
  17559. */
  17560. function Node(name, scene) {
  17561. if (scene === void 0) { scene = null; }
  17562. /**
  17563. * Gets or sets a string used to store user defined state for the node
  17564. */
  17565. this.state = "";
  17566. /**
  17567. * Gets or sets an object used to store user defined information for the node
  17568. */
  17569. this.metadata = null;
  17570. /**
  17571. * Gets or sets a boolean used to define if the node must be serialized
  17572. */
  17573. this.doNotSerialize = false;
  17574. /** @hidden */
  17575. this._isDisposed = false;
  17576. /**
  17577. * Gets a list of Animations associated with the node
  17578. */
  17579. this.animations = new Array();
  17580. this._ranges = {};
  17581. this._isEnabled = true;
  17582. this._isReady = true;
  17583. /** @hidden */
  17584. this._currentRenderId = -1;
  17585. this._parentRenderId = -1;
  17586. this._childRenderId = -1;
  17587. this._animationPropertiesOverride = null;
  17588. /**
  17589. * An event triggered when the mesh is disposed
  17590. */
  17591. this.onDisposeObservable = new BABYLON.Observable();
  17592. // Behaviors
  17593. this._behaviors = new Array();
  17594. this.name = name;
  17595. this.id = name;
  17596. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17597. this.uniqueId = this._scene.getUniqueId();
  17598. this._initCache();
  17599. }
  17600. /**
  17601. * Gets a boolean indicating if the node has been disposed
  17602. * @returns true if the node was disposed
  17603. */
  17604. Node.prototype.isDisposed = function () {
  17605. return this._isDisposed;
  17606. };
  17607. Object.defineProperty(Node.prototype, "parent", {
  17608. get: function () {
  17609. return this._parentNode;
  17610. },
  17611. /**
  17612. * Gets or sets the parent of the node
  17613. */
  17614. set: function (parent) {
  17615. if (this._parentNode === parent) {
  17616. return;
  17617. }
  17618. // Remove self from list of children of parent
  17619. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17620. var index = this._parentNode._children.indexOf(this);
  17621. if (index !== -1) {
  17622. this._parentNode._children.splice(index, 1);
  17623. }
  17624. }
  17625. // Store new parent
  17626. this._parentNode = parent;
  17627. // Add as child to new parent
  17628. if (this._parentNode) {
  17629. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17630. this._parentNode._children = new Array();
  17631. }
  17632. this._parentNode._children.push(this);
  17633. }
  17634. },
  17635. enumerable: true,
  17636. configurable: true
  17637. });
  17638. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17639. /**
  17640. * Gets or sets the animation properties override
  17641. */
  17642. get: function () {
  17643. if (!this._animationPropertiesOverride) {
  17644. return this._scene.animationPropertiesOverride;
  17645. }
  17646. return this._animationPropertiesOverride;
  17647. },
  17648. set: function (value) {
  17649. this._animationPropertiesOverride = value;
  17650. },
  17651. enumerable: true,
  17652. configurable: true
  17653. });
  17654. /**
  17655. * Gets a string idenfifying the name of the class
  17656. * @returns "Node" string
  17657. */
  17658. Node.prototype.getClassName = function () {
  17659. return "Node";
  17660. };
  17661. Object.defineProperty(Node.prototype, "onDispose", {
  17662. /**
  17663. * Sets a callback that will be raised when the node will be disposed
  17664. */
  17665. set: function (callback) {
  17666. if (this._onDisposeObserver) {
  17667. this.onDisposeObservable.remove(this._onDisposeObserver);
  17668. }
  17669. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17670. },
  17671. enumerable: true,
  17672. configurable: true
  17673. });
  17674. /**
  17675. * Gets the scene of the node
  17676. * @returns a {BABYLON.Scene}
  17677. */
  17678. Node.prototype.getScene = function () {
  17679. return this._scene;
  17680. };
  17681. /**
  17682. * Gets the engine of the node
  17683. * @returns a {BABYLON.Engine}
  17684. */
  17685. Node.prototype.getEngine = function () {
  17686. return this._scene.getEngine();
  17687. };
  17688. /**
  17689. * Attach a behavior to the node
  17690. * @see http://doc.babylonjs.com/features/behaviour
  17691. * @param behavior defines the behavior to attach
  17692. * @returns the current Node
  17693. */
  17694. Node.prototype.addBehavior = function (behavior) {
  17695. var _this = this;
  17696. var index = this._behaviors.indexOf(behavior);
  17697. if (index !== -1) {
  17698. return this;
  17699. }
  17700. behavior.init();
  17701. if (this._scene.isLoading) {
  17702. // We defer the attach when the scene will be loaded
  17703. this._scene.onDataLoadedObservable.addOnce(function () {
  17704. behavior.attach(_this);
  17705. });
  17706. }
  17707. else {
  17708. behavior.attach(this);
  17709. }
  17710. this._behaviors.push(behavior);
  17711. return this;
  17712. };
  17713. /**
  17714. * Remove an attached behavior
  17715. * @see http://doc.babylonjs.com/features/behaviour
  17716. * @param behavior defines the behavior to attach
  17717. * @returns the current Node
  17718. */
  17719. Node.prototype.removeBehavior = function (behavior) {
  17720. var index = this._behaviors.indexOf(behavior);
  17721. if (index === -1) {
  17722. return this;
  17723. }
  17724. this._behaviors[index].detach();
  17725. this._behaviors.splice(index, 1);
  17726. return this;
  17727. };
  17728. Object.defineProperty(Node.prototype, "behaviors", {
  17729. /**
  17730. * Gets the list of attached behaviors
  17731. * @see http://doc.babylonjs.com/features/behaviour
  17732. */
  17733. get: function () {
  17734. return this._behaviors;
  17735. },
  17736. enumerable: true,
  17737. configurable: true
  17738. });
  17739. /**
  17740. * Gets an attached behavior by name
  17741. * @param name defines the name of the behavior to look for
  17742. * @see http://doc.babylonjs.com/features/behaviour
  17743. * @returns null if behavior was not found else the requested behavior
  17744. */
  17745. Node.prototype.getBehaviorByName = function (name) {
  17746. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17747. var behavior = _a[_i];
  17748. if (behavior.name === name) {
  17749. return behavior;
  17750. }
  17751. }
  17752. return null;
  17753. };
  17754. /**
  17755. * Returns the world matrix of the node
  17756. * @returns a matrix containing the node's world matrix
  17757. */
  17758. Node.prototype.getWorldMatrix = function () {
  17759. return BABYLON.Matrix.Identity();
  17760. };
  17761. /** @hidden */
  17762. Node.prototype._getWorldMatrixDeterminant = function () {
  17763. return 1;
  17764. };
  17765. // override it in derived class if you add new variables to the cache
  17766. // and call the parent class method
  17767. /** @hidden */
  17768. Node.prototype._initCache = function () {
  17769. this._cache = {};
  17770. this._cache.parent = undefined;
  17771. };
  17772. /** @hidden */
  17773. Node.prototype.updateCache = function (force) {
  17774. if (!force && this.isSynchronized())
  17775. return;
  17776. this._cache.parent = this.parent;
  17777. this._updateCache();
  17778. };
  17779. // override it in derived class if you add new variables to the cache
  17780. // and call the parent class method if !ignoreParentClass
  17781. /** @hidden */
  17782. Node.prototype._updateCache = function (ignoreParentClass) {
  17783. };
  17784. // override it in derived class if you add new variables to the cache
  17785. /** @hidden */
  17786. Node.prototype._isSynchronized = function () {
  17787. return true;
  17788. };
  17789. /** @hidden */
  17790. Node.prototype._markSyncedWithParent = function () {
  17791. if (this.parent) {
  17792. this._parentRenderId = this.parent._childRenderId;
  17793. }
  17794. };
  17795. /** @hidden */
  17796. Node.prototype.isSynchronizedWithParent = function () {
  17797. if (!this.parent) {
  17798. return true;
  17799. }
  17800. if (this._parentRenderId !== this.parent._childRenderId) {
  17801. return false;
  17802. }
  17803. return this.parent.isSynchronized();
  17804. };
  17805. /** @hidden */
  17806. Node.prototype.isSynchronized = function (updateCache) {
  17807. var check = this.hasNewParent();
  17808. check = check || !this.isSynchronizedWithParent();
  17809. check = check || !this._isSynchronized();
  17810. if (updateCache)
  17811. this.updateCache(true);
  17812. return !check;
  17813. };
  17814. /** @hidden */
  17815. Node.prototype.hasNewParent = function (update) {
  17816. if (this._cache.parent === this.parent)
  17817. return false;
  17818. if (update)
  17819. this._cache.parent = this.parent;
  17820. return true;
  17821. };
  17822. /**
  17823. * Is this node ready to be used/rendered
  17824. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17825. * @return true if the node is ready
  17826. */
  17827. Node.prototype.isReady = function (completeCheck) {
  17828. if (completeCheck === void 0) { completeCheck = false; }
  17829. return this._isReady;
  17830. };
  17831. /**
  17832. * Is this node enabled?
  17833. * 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
  17834. * @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
  17835. * @return whether this node (and its parent) is enabled
  17836. */
  17837. Node.prototype.isEnabled = function (checkAncestors) {
  17838. if (checkAncestors === void 0) { checkAncestors = true; }
  17839. if (checkAncestors === false) {
  17840. return this._isEnabled;
  17841. }
  17842. if (this._isEnabled === false) {
  17843. return false;
  17844. }
  17845. if (this.parent !== undefined && this.parent !== null) {
  17846. return this.parent.isEnabled(checkAncestors);
  17847. }
  17848. return true;
  17849. };
  17850. /**
  17851. * Set the enabled state of this node
  17852. * @param value defines the new enabled state
  17853. */
  17854. Node.prototype.setEnabled = function (value) {
  17855. this._isEnabled = value;
  17856. };
  17857. /**
  17858. * Is this node a descendant of the given node?
  17859. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17860. * @param ancestor defines the parent node to inspect
  17861. * @returns a boolean indicating if this node is a descendant of the given node
  17862. */
  17863. Node.prototype.isDescendantOf = function (ancestor) {
  17864. if (this.parent) {
  17865. if (this.parent === ancestor) {
  17866. return true;
  17867. }
  17868. return this.parent.isDescendantOf(ancestor);
  17869. }
  17870. return false;
  17871. };
  17872. /** @hidden */
  17873. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17874. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17875. if (!this._children) {
  17876. return;
  17877. }
  17878. for (var index = 0; index < this._children.length; index++) {
  17879. var item = this._children[index];
  17880. if (!predicate || predicate(item)) {
  17881. results.push(item);
  17882. }
  17883. if (!directDescendantsOnly) {
  17884. item._getDescendants(results, false, predicate);
  17885. }
  17886. }
  17887. };
  17888. /**
  17889. * Will return all nodes that have this node as ascendant
  17890. * @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
  17891. * @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
  17892. * @return all children nodes of all types
  17893. */
  17894. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17895. var results = new Array();
  17896. this._getDescendants(results, directDescendantsOnly, predicate);
  17897. return results;
  17898. };
  17899. /**
  17900. * Get all child-meshes of this node
  17901. * @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
  17902. * @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
  17903. * @returns an array of {BABYLON.AbstractMesh}
  17904. */
  17905. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17906. var results = [];
  17907. this._getDescendants(results, directDescendantsOnly, function (node) {
  17908. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17909. });
  17910. return results;
  17911. };
  17912. /**
  17913. * Get all child-transformNodes of this node
  17914. * @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
  17915. * @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
  17916. * @returns an array of {BABYLON.TransformNode}
  17917. */
  17918. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17919. var results = [];
  17920. this._getDescendants(results, directDescendantsOnly, function (node) {
  17921. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17922. });
  17923. return results;
  17924. };
  17925. /**
  17926. * Get all direct children of this node
  17927. * @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
  17928. * @returns an array of {BABYLON.Node}
  17929. */
  17930. Node.prototype.getChildren = function (predicate) {
  17931. return this.getDescendants(true, predicate);
  17932. };
  17933. /** @hidden */
  17934. Node.prototype._setReady = function (state) {
  17935. if (state === this._isReady) {
  17936. return;
  17937. }
  17938. if (!state) {
  17939. this._isReady = false;
  17940. return;
  17941. }
  17942. if (this.onReady) {
  17943. this.onReady(this);
  17944. }
  17945. this._isReady = true;
  17946. };
  17947. /**
  17948. * Get an animation by name
  17949. * @param name defines the name of the animation to look for
  17950. * @returns null if not found else the requested animation
  17951. */
  17952. Node.prototype.getAnimationByName = function (name) {
  17953. for (var i = 0; i < this.animations.length; i++) {
  17954. var animation = this.animations[i];
  17955. if (animation.name === name) {
  17956. return animation;
  17957. }
  17958. }
  17959. return null;
  17960. };
  17961. /**
  17962. * Creates an animation range for this node
  17963. * @param name defines the name of the range
  17964. * @param from defines the starting key
  17965. * @param to defines the end key
  17966. */
  17967. Node.prototype.createAnimationRange = function (name, from, to) {
  17968. // check name not already in use
  17969. if (!this._ranges[name]) {
  17970. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17971. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17972. if (this.animations[i]) {
  17973. this.animations[i].createRange(name, from, to);
  17974. }
  17975. }
  17976. }
  17977. };
  17978. /**
  17979. * Delete a specific animation range
  17980. * @param name defines the name of the range to delete
  17981. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17982. */
  17983. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17984. if (deleteFrames === void 0) { deleteFrames = true; }
  17985. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17986. if (this.animations[i]) {
  17987. this.animations[i].deleteRange(name, deleteFrames);
  17988. }
  17989. }
  17990. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17991. };
  17992. /**
  17993. * Get an animation range by name
  17994. * @param name defines the name of the animation range to look for
  17995. * @returns null if not found else the requested animation range
  17996. */
  17997. Node.prototype.getAnimationRange = function (name) {
  17998. return this._ranges[name];
  17999. };
  18000. /**
  18001. * Will start the animation sequence
  18002. * @param name defines the range frames for animation sequence
  18003. * @param loop defines if the animation should loop (false by default)
  18004. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18005. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18006. * @returns the object created for this animation. If range does not exist, it will return null
  18007. */
  18008. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18009. var range = this.getAnimationRange(name);
  18010. if (!range) {
  18011. return null;
  18012. }
  18013. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18014. };
  18015. /**
  18016. * Serialize animation ranges into a JSON compatible object
  18017. * @returns serialization object
  18018. */
  18019. Node.prototype.serializeAnimationRanges = function () {
  18020. var serializationRanges = [];
  18021. for (var name in this._ranges) {
  18022. var localRange = this._ranges[name];
  18023. if (!localRange) {
  18024. continue;
  18025. }
  18026. var range = {};
  18027. range.name = name;
  18028. range.from = localRange.from;
  18029. range.to = localRange.to;
  18030. serializationRanges.push(range);
  18031. }
  18032. return serializationRanges;
  18033. };
  18034. /**
  18035. * Computes the world matrix of the node
  18036. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18037. * @returns the world matrix
  18038. */
  18039. Node.prototype.computeWorldMatrix = function (force) {
  18040. return BABYLON.Matrix.Identity();
  18041. };
  18042. /**
  18043. * Releases resources associated with this node.
  18044. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18045. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18046. */
  18047. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18048. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18049. if (!doNotRecurse) {
  18050. var nodes = this.getDescendants(true);
  18051. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18052. var node = nodes_1[_i];
  18053. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18054. }
  18055. }
  18056. else {
  18057. var transformNodes = this.getChildTransformNodes(true);
  18058. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18059. var transformNode = transformNodes_1[_a];
  18060. transformNode.parent = null;
  18061. transformNode.computeWorldMatrix(true);
  18062. }
  18063. }
  18064. this.parent = null;
  18065. // Callback
  18066. this.onDisposeObservable.notifyObservers(this);
  18067. this.onDisposeObservable.clear();
  18068. // Behaviors
  18069. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18070. var behavior = _c[_b];
  18071. behavior.detach();
  18072. }
  18073. this._behaviors = [];
  18074. this._isDisposed = true;
  18075. };
  18076. /**
  18077. * Parse animation range data from a serialization object and store them into a given node
  18078. * @param node defines where to store the animation ranges
  18079. * @param parsedNode defines the serialization object to read data from
  18080. * @param scene defines the hosting scene
  18081. */
  18082. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18083. if (parsedNode.ranges) {
  18084. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18085. var data = parsedNode.ranges[index];
  18086. node.createAnimationRange(data.name, data.from, data.to);
  18087. }
  18088. }
  18089. };
  18090. __decorate([
  18091. BABYLON.serialize()
  18092. ], Node.prototype, "name", void 0);
  18093. __decorate([
  18094. BABYLON.serialize()
  18095. ], Node.prototype, "id", void 0);
  18096. __decorate([
  18097. BABYLON.serialize()
  18098. ], Node.prototype, "uniqueId", void 0);
  18099. __decorate([
  18100. BABYLON.serialize()
  18101. ], Node.prototype, "state", void 0);
  18102. __decorate([
  18103. BABYLON.serialize()
  18104. ], Node.prototype, "metadata", void 0);
  18105. return Node;
  18106. }());
  18107. BABYLON.Node = Node;
  18108. })(BABYLON || (BABYLON = {}));
  18109. //# sourceMappingURL=babylon.node.js.map
  18110. var BABYLON;
  18111. (function (BABYLON) {
  18112. var BoundingSphere = /** @class */ (function () {
  18113. /**
  18114. * Creates a new bounding sphere
  18115. * @param min defines the minimum vector (in local space)
  18116. * @param max defines the maximum vector (in local space)
  18117. */
  18118. function BoundingSphere(min, max) {
  18119. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18120. this.reConstruct(min, max);
  18121. }
  18122. /**
  18123. * Recreates the entire bounding sphere from scratch
  18124. * @param min defines the new minimum vector (in local space)
  18125. * @param max defines the new maximum vector (in local space)
  18126. */
  18127. BoundingSphere.prototype.reConstruct = function (min, max) {
  18128. this.minimum = min.clone();
  18129. this.maximum = max.clone();
  18130. var distance = BABYLON.Vector3.Distance(min, max);
  18131. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18132. this.radius = distance * 0.5;
  18133. this.centerWorld = BABYLON.Vector3.Zero();
  18134. this._update(BABYLON.Matrix.Identity());
  18135. };
  18136. // Methods
  18137. BoundingSphere.prototype._update = function (world) {
  18138. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18139. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18140. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18141. };
  18142. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18143. for (var i = 0; i < 6; i++) {
  18144. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18145. return false;
  18146. }
  18147. return true;
  18148. };
  18149. BoundingSphere.prototype.intersectsPoint = function (point) {
  18150. var x = this.centerWorld.x - point.x;
  18151. var y = this.centerWorld.y - point.y;
  18152. var z = this.centerWorld.z - point.z;
  18153. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18154. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18155. return false;
  18156. return true;
  18157. };
  18158. // Statics
  18159. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18160. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18161. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18162. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18163. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18164. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18165. return false;
  18166. return true;
  18167. };
  18168. return BoundingSphere;
  18169. }());
  18170. BABYLON.BoundingSphere = BoundingSphere;
  18171. })(BABYLON || (BABYLON = {}));
  18172. //# sourceMappingURL=babylon.boundingSphere.js.map
  18173. var BABYLON;
  18174. (function (BABYLON) {
  18175. var BoundingBox = /** @class */ (function () {
  18176. /**
  18177. * Creates a new bounding box
  18178. * @param min defines the minimum vector (in local space)
  18179. * @param max defines the maximum vector (in local space)
  18180. */
  18181. function BoundingBox(min, max) {
  18182. this.vectorsWorld = new Array();
  18183. this.reConstruct(min, max);
  18184. }
  18185. // Methods
  18186. /**
  18187. * Recreates the entire bounding box from scratch
  18188. * @param min defines the new minimum vector (in local space)
  18189. * @param max defines the new maximum vector (in local space)
  18190. */
  18191. BoundingBox.prototype.reConstruct = function (min, max) {
  18192. this.minimum = min.clone();
  18193. this.maximum = max.clone();
  18194. // Bounding vectors
  18195. this.vectors = new Array();
  18196. this.vectors.push(this.minimum.clone());
  18197. this.vectors.push(this.maximum.clone());
  18198. this.vectors.push(this.minimum.clone());
  18199. this.vectors[2].x = this.maximum.x;
  18200. this.vectors.push(this.minimum.clone());
  18201. this.vectors[3].y = this.maximum.y;
  18202. this.vectors.push(this.minimum.clone());
  18203. this.vectors[4].z = this.maximum.z;
  18204. this.vectors.push(this.maximum.clone());
  18205. this.vectors[5].z = this.minimum.z;
  18206. this.vectors.push(this.maximum.clone());
  18207. this.vectors[6].x = this.minimum.x;
  18208. this.vectors.push(this.maximum.clone());
  18209. this.vectors[7].y = this.minimum.y;
  18210. // OBB
  18211. this.center = this.maximum.add(this.minimum).scale(0.5);
  18212. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18213. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18214. // World
  18215. for (var index = 0; index < this.vectors.length; index++) {
  18216. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18217. }
  18218. this.minimumWorld = BABYLON.Vector3.Zero();
  18219. this.maximumWorld = BABYLON.Vector3.Zero();
  18220. this.centerWorld = BABYLON.Vector3.Zero();
  18221. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18222. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18223. };
  18224. BoundingBox.prototype.getWorldMatrix = function () {
  18225. return this._worldMatrix;
  18226. };
  18227. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18228. this._worldMatrix.copyFrom(matrix);
  18229. return this;
  18230. };
  18231. BoundingBox.prototype._update = function (world) {
  18232. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18233. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18234. for (var index = 0; index < this.vectors.length; index++) {
  18235. var v = this.vectorsWorld[index];
  18236. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18237. if (v.x < this.minimumWorld.x)
  18238. this.minimumWorld.x = v.x;
  18239. if (v.y < this.minimumWorld.y)
  18240. this.minimumWorld.y = v.y;
  18241. if (v.z < this.minimumWorld.z)
  18242. this.minimumWorld.z = v.z;
  18243. if (v.x > this.maximumWorld.x)
  18244. this.maximumWorld.x = v.x;
  18245. if (v.y > this.maximumWorld.y)
  18246. this.maximumWorld.y = v.y;
  18247. if (v.z > this.maximumWorld.z)
  18248. this.maximumWorld.z = v.z;
  18249. }
  18250. // Extend
  18251. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18252. this.extendSizeWorld.scaleInPlace(0.5);
  18253. // OBB
  18254. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18255. this.centerWorld.scaleInPlace(0.5);
  18256. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18257. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18258. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18259. this._worldMatrix = world;
  18260. };
  18261. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18262. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18263. };
  18264. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18265. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18266. };
  18267. BoundingBox.prototype.intersectsPoint = function (point) {
  18268. var delta = -BABYLON.Epsilon;
  18269. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18270. return false;
  18271. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18272. return false;
  18273. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18274. return false;
  18275. return true;
  18276. };
  18277. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18278. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18279. };
  18280. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18281. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18282. return false;
  18283. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18284. return false;
  18285. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18286. return false;
  18287. return true;
  18288. };
  18289. // Statics
  18290. BoundingBox.Intersects = function (box0, box1) {
  18291. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18292. return false;
  18293. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18294. return false;
  18295. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18296. return false;
  18297. return true;
  18298. };
  18299. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18300. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18301. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18302. return (num <= (sphereRadius * sphereRadius));
  18303. };
  18304. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18305. for (var p = 0; p < 6; p++) {
  18306. for (var i = 0; i < 8; i++) {
  18307. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18308. return false;
  18309. }
  18310. }
  18311. }
  18312. return true;
  18313. };
  18314. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18315. for (var p = 0; p < 6; p++) {
  18316. var inCount = 8;
  18317. for (var i = 0; i < 8; i++) {
  18318. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18319. --inCount;
  18320. }
  18321. else {
  18322. break;
  18323. }
  18324. }
  18325. if (inCount === 0)
  18326. return false;
  18327. }
  18328. return true;
  18329. };
  18330. return BoundingBox;
  18331. }());
  18332. BABYLON.BoundingBox = BoundingBox;
  18333. })(BABYLON || (BABYLON = {}));
  18334. //# sourceMappingURL=babylon.boundingBox.js.map
  18335. var BABYLON;
  18336. (function (BABYLON) {
  18337. var computeBoxExtents = function (axis, box) {
  18338. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18339. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18340. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18341. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18342. var r = r0 + r1 + r2;
  18343. return {
  18344. min: p - r,
  18345. max: p + r
  18346. };
  18347. };
  18348. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18349. var axisOverlap = function (axis, box0, box1) {
  18350. var result0 = computeBoxExtents(axis, box0);
  18351. var result1 = computeBoxExtents(axis, box1);
  18352. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18353. };
  18354. var BoundingInfo = /** @class */ (function () {
  18355. function BoundingInfo(minimum, maximum) {
  18356. this.minimum = minimum;
  18357. this.maximum = maximum;
  18358. this._isLocked = false;
  18359. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18360. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18361. }
  18362. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18363. get: function () {
  18364. return this._isLocked;
  18365. },
  18366. set: function (value) {
  18367. this._isLocked = value;
  18368. },
  18369. enumerable: true,
  18370. configurable: true
  18371. });
  18372. // Methods
  18373. BoundingInfo.prototype.update = function (world) {
  18374. if (this._isLocked) {
  18375. return;
  18376. }
  18377. this.boundingBox._update(world);
  18378. this.boundingSphere._update(world);
  18379. };
  18380. /**
  18381. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18382. * @param center New center of the bounding info
  18383. * @param extend New extend of the bounding info
  18384. */
  18385. BoundingInfo.prototype.centerOn = function (center, extend) {
  18386. this.minimum = center.subtract(extend);
  18387. this.maximum = center.add(extend);
  18388. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18389. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18390. return this;
  18391. };
  18392. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18393. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18394. return false;
  18395. return this.boundingBox.isInFrustum(frustumPlanes);
  18396. };
  18397. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18398. /**
  18399. * Gets the world distance between the min and max points of the bounding box
  18400. */
  18401. get: function () {
  18402. var boundingBox = this.boundingBox;
  18403. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18404. return size.length();
  18405. },
  18406. enumerable: true,
  18407. configurable: true
  18408. });
  18409. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18410. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18411. };
  18412. BoundingInfo.prototype._checkCollision = function (collider) {
  18413. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18414. };
  18415. BoundingInfo.prototype.intersectsPoint = function (point) {
  18416. if (!this.boundingSphere.centerWorld) {
  18417. return false;
  18418. }
  18419. if (!this.boundingSphere.intersectsPoint(point)) {
  18420. return false;
  18421. }
  18422. if (!this.boundingBox.intersectsPoint(point)) {
  18423. return false;
  18424. }
  18425. return true;
  18426. };
  18427. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18428. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18429. return false;
  18430. }
  18431. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18432. return false;
  18433. }
  18434. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18435. return false;
  18436. }
  18437. if (!precise) {
  18438. return true;
  18439. }
  18440. var box0 = this.boundingBox;
  18441. var box1 = boundingInfo.boundingBox;
  18442. if (!axisOverlap(box0.directions[0], box0, box1))
  18443. return false;
  18444. if (!axisOverlap(box0.directions[1], box0, box1))
  18445. return false;
  18446. if (!axisOverlap(box0.directions[2], box0, box1))
  18447. return false;
  18448. if (!axisOverlap(box1.directions[0], box0, box1))
  18449. return false;
  18450. if (!axisOverlap(box1.directions[1], box0, box1))
  18451. return false;
  18452. if (!axisOverlap(box1.directions[2], box0, box1))
  18453. return false;
  18454. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18455. return false;
  18456. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18457. return false;
  18458. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18459. return false;
  18460. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18461. return false;
  18462. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18463. return false;
  18464. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18465. return false;
  18466. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18467. return false;
  18468. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18469. return false;
  18470. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18471. return false;
  18472. return true;
  18473. };
  18474. return BoundingInfo;
  18475. }());
  18476. BABYLON.BoundingInfo = BoundingInfo;
  18477. })(BABYLON || (BABYLON = {}));
  18478. //# sourceMappingURL=babylon.boundingInfo.js.map
  18479. var BABYLON;
  18480. (function (BABYLON) {
  18481. var TransformNode = /** @class */ (function (_super) {
  18482. __extends(TransformNode, _super);
  18483. function TransformNode(name, scene, isPure) {
  18484. if (scene === void 0) { scene = null; }
  18485. if (isPure === void 0) { isPure = true; }
  18486. var _this = _super.call(this, name, scene) || this;
  18487. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18488. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18489. _this._up = new BABYLON.Vector3(0, 1, 0);
  18490. _this._right = new BABYLON.Vector3(1, 0, 0);
  18491. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18492. // Properties
  18493. _this._rotation = BABYLON.Vector3.Zero();
  18494. _this._scaling = BABYLON.Vector3.One();
  18495. _this._isDirty = false;
  18496. /**
  18497. * Set the billboard mode. Default is 0.
  18498. *
  18499. * | Value | Type | Description |
  18500. * | --- | --- | --- |
  18501. * | 0 | BILLBOARDMODE_NONE | |
  18502. * | 1 | BILLBOARDMODE_X | |
  18503. * | 2 | BILLBOARDMODE_Y | |
  18504. * | 4 | BILLBOARDMODE_Z | |
  18505. * | 7 | BILLBOARDMODE_ALL | |
  18506. *
  18507. */
  18508. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18509. _this.scalingDeterminant = 1;
  18510. _this.infiniteDistance = false;
  18511. /**
  18512. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18513. * By default the system will update normals to compensate
  18514. */
  18515. _this.ignoreNonUniformScaling = false;
  18516. _this.position = BABYLON.Vector3.Zero();
  18517. _this._localWorld = BABYLON.Matrix.Zero();
  18518. _this._worldMatrix = BABYLON.Matrix.Zero();
  18519. _this._worldMatrixDeterminant = 0;
  18520. _this._absolutePosition = BABYLON.Vector3.Zero();
  18521. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18522. _this._postMultiplyPivotMatrix = false;
  18523. _this._isWorldMatrixFrozen = false;
  18524. /**
  18525. * An event triggered after the world matrix is updated
  18526. */
  18527. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18528. _this._nonUniformScaling = false;
  18529. if (isPure) {
  18530. _this.getScene().addTransformNode(_this);
  18531. }
  18532. return _this;
  18533. }
  18534. /**
  18535. * Gets a string idenfifying the name of the class
  18536. * @returns "TransformNode" string
  18537. */
  18538. TransformNode.prototype.getClassName = function () {
  18539. return "TransformNode";
  18540. };
  18541. Object.defineProperty(TransformNode.prototype, "rotation", {
  18542. /**
  18543. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18544. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18545. * Default : (0.0, 0.0, 0.0)
  18546. */
  18547. get: function () {
  18548. return this._rotation;
  18549. },
  18550. set: function (newRotation) {
  18551. this._rotation = newRotation;
  18552. },
  18553. enumerable: true,
  18554. configurable: true
  18555. });
  18556. Object.defineProperty(TransformNode.prototype, "scaling", {
  18557. /**
  18558. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18559. * Default : (1.0, 1.0, 1.0)
  18560. */
  18561. get: function () {
  18562. return this._scaling;
  18563. },
  18564. /**
  18565. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18566. * Default : (1.0, 1.0, 1.0)
  18567. */
  18568. set: function (newScaling) {
  18569. this._scaling = newScaling;
  18570. },
  18571. enumerable: true,
  18572. configurable: true
  18573. });
  18574. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18575. /**
  18576. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18577. * It's null by default.
  18578. * 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)
  18579. */
  18580. get: function () {
  18581. return this._rotationQuaternion;
  18582. },
  18583. set: function (quaternion) {
  18584. this._rotationQuaternion = quaternion;
  18585. //reset the rotation vector.
  18586. if (quaternion && this.rotation.length()) {
  18587. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18588. }
  18589. },
  18590. enumerable: true,
  18591. configurable: true
  18592. });
  18593. Object.defineProperty(TransformNode.prototype, "forward", {
  18594. /**
  18595. * The forward direction of that transform in world space.
  18596. */
  18597. get: function () {
  18598. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18599. },
  18600. enumerable: true,
  18601. configurable: true
  18602. });
  18603. Object.defineProperty(TransformNode.prototype, "up", {
  18604. /**
  18605. * The up direction of that transform in world space.
  18606. */
  18607. get: function () {
  18608. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18609. },
  18610. enumerable: true,
  18611. configurable: true
  18612. });
  18613. Object.defineProperty(TransformNode.prototype, "right", {
  18614. /**
  18615. * The right direction of that transform in world space.
  18616. */
  18617. get: function () {
  18618. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18619. },
  18620. enumerable: true,
  18621. configurable: true
  18622. });
  18623. /**
  18624. * Returns the latest update of the World matrix
  18625. * Returns a Matrix.
  18626. */
  18627. TransformNode.prototype.getWorldMatrix = function () {
  18628. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18629. this.computeWorldMatrix();
  18630. }
  18631. return this._worldMatrix;
  18632. };
  18633. /** @hidden */
  18634. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18635. return this._worldMatrixDeterminant;
  18636. };
  18637. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18638. /**
  18639. * Returns directly the latest state of the mesh World matrix.
  18640. * A Matrix is returned.
  18641. */
  18642. get: function () {
  18643. return this._worldMatrix;
  18644. },
  18645. enumerable: true,
  18646. configurable: true
  18647. });
  18648. /**
  18649. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18650. * Returns the TransformNode.
  18651. */
  18652. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18653. this._poseMatrix.copyFrom(matrix);
  18654. return this;
  18655. };
  18656. /**
  18657. * Returns the mesh Pose matrix.
  18658. * Returned object : Matrix
  18659. */
  18660. TransformNode.prototype.getPoseMatrix = function () {
  18661. return this._poseMatrix;
  18662. };
  18663. TransformNode.prototype._isSynchronized = function () {
  18664. if (this._isDirty) {
  18665. return false;
  18666. }
  18667. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18668. return false;
  18669. if (this._cache.pivotMatrixUpdated) {
  18670. return false;
  18671. }
  18672. if (this.infiniteDistance) {
  18673. return false;
  18674. }
  18675. if (!this._cache.position.equals(this.position))
  18676. return false;
  18677. if (this.rotationQuaternion) {
  18678. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18679. return false;
  18680. }
  18681. if (!this._cache.rotation.equals(this.rotation))
  18682. return false;
  18683. if (!this._cache.scaling.equals(this.scaling))
  18684. return false;
  18685. return true;
  18686. };
  18687. TransformNode.prototype._initCache = function () {
  18688. _super.prototype._initCache.call(this);
  18689. this._cache.localMatrixUpdated = false;
  18690. this._cache.position = BABYLON.Vector3.Zero();
  18691. this._cache.scaling = BABYLON.Vector3.Zero();
  18692. this._cache.rotation = BABYLON.Vector3.Zero();
  18693. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18694. this._cache.billboardMode = -1;
  18695. };
  18696. TransformNode.prototype.markAsDirty = function (property) {
  18697. if (property === "rotation") {
  18698. this.rotationQuaternion = null;
  18699. }
  18700. this._currentRenderId = Number.MAX_VALUE;
  18701. this._isDirty = true;
  18702. return this;
  18703. };
  18704. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18705. /**
  18706. * Returns the current mesh absolute position.
  18707. * Retuns a Vector3.
  18708. */
  18709. get: function () {
  18710. return this._absolutePosition;
  18711. },
  18712. enumerable: true,
  18713. configurable: true
  18714. });
  18715. /**
  18716. * Sets a new matrix to apply before all other transformation
  18717. * @param matrix defines the transform matrix
  18718. * @returns the current TransformNode
  18719. */
  18720. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18721. return this.setPivotMatrix(matrix, false);
  18722. };
  18723. /**
  18724. * Sets a new pivot matrix to the current node
  18725. * @param matrix defines the new pivot matrix to use
  18726. * @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
  18727. * @returns the current TransformNode
  18728. */
  18729. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18730. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18731. this._pivotMatrix = matrix.clone();
  18732. this._cache.pivotMatrixUpdated = true;
  18733. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18734. if (this._postMultiplyPivotMatrix) {
  18735. if (!this._pivotMatrixInverse) {
  18736. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18737. }
  18738. else {
  18739. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18740. }
  18741. }
  18742. return this;
  18743. };
  18744. /**
  18745. * Returns the mesh pivot matrix.
  18746. * Default : Identity.
  18747. * A Matrix is returned.
  18748. */
  18749. TransformNode.prototype.getPivotMatrix = function () {
  18750. return this._pivotMatrix;
  18751. };
  18752. /**
  18753. * Prevents the World matrix to be computed any longer.
  18754. * Returns the TransformNode.
  18755. */
  18756. TransformNode.prototype.freezeWorldMatrix = function () {
  18757. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18758. this.computeWorldMatrix(true);
  18759. this._isWorldMatrixFrozen = true;
  18760. return this;
  18761. };
  18762. /**
  18763. * Allows back the World matrix computation.
  18764. * Returns the TransformNode.
  18765. */
  18766. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18767. this._isWorldMatrixFrozen = false;
  18768. this.computeWorldMatrix(true);
  18769. return this;
  18770. };
  18771. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18772. /**
  18773. * True if the World matrix has been frozen.
  18774. * Returns a boolean.
  18775. */
  18776. get: function () {
  18777. return this._isWorldMatrixFrozen;
  18778. },
  18779. enumerable: true,
  18780. configurable: true
  18781. });
  18782. /**
  18783. * Retuns the mesh absolute position in the World.
  18784. * Returns a Vector3.
  18785. */
  18786. TransformNode.prototype.getAbsolutePosition = function () {
  18787. this.computeWorldMatrix();
  18788. return this._absolutePosition;
  18789. };
  18790. /**
  18791. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18792. * Returns the TransformNode.
  18793. */
  18794. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18795. if (!absolutePosition) {
  18796. return this;
  18797. }
  18798. var absolutePositionX;
  18799. var absolutePositionY;
  18800. var absolutePositionZ;
  18801. if (absolutePosition.x === undefined) {
  18802. if (arguments.length < 3) {
  18803. return this;
  18804. }
  18805. absolutePositionX = arguments[0];
  18806. absolutePositionY = arguments[1];
  18807. absolutePositionZ = arguments[2];
  18808. }
  18809. else {
  18810. absolutePositionX = absolutePosition.x;
  18811. absolutePositionY = absolutePosition.y;
  18812. absolutePositionZ = absolutePosition.z;
  18813. }
  18814. if (this.parent) {
  18815. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18816. invertParentWorldMatrix.invert();
  18817. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18818. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18819. }
  18820. else {
  18821. this.position.x = absolutePositionX;
  18822. this.position.y = absolutePositionY;
  18823. this.position.z = absolutePositionZ;
  18824. }
  18825. return this;
  18826. };
  18827. /**
  18828. * Sets the mesh position in its local space.
  18829. * Returns the TransformNode.
  18830. */
  18831. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18832. this.computeWorldMatrix();
  18833. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18834. return this;
  18835. };
  18836. /**
  18837. * Returns the mesh position in the local space from the current World matrix values.
  18838. * Returns a new Vector3.
  18839. */
  18840. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18841. this.computeWorldMatrix();
  18842. var invLocalWorldMatrix = this._localWorld.clone();
  18843. invLocalWorldMatrix.invert();
  18844. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18845. };
  18846. /**
  18847. * Translates the mesh along the passed Vector3 in its local space.
  18848. * Returns the TransformNode.
  18849. */
  18850. TransformNode.prototype.locallyTranslate = function (vector3) {
  18851. this.computeWorldMatrix(true);
  18852. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18853. return this;
  18854. };
  18855. /**
  18856. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18857. * @param targetPoint the position (must be in same space as current mesh) to look at
  18858. * @param yawCor optional yaw (y-axis) correction in radians
  18859. * @param pitchCor optional pitch (x-axis) correction in radians
  18860. * @param rollCor optional roll (z-axis) correction in radians
  18861. * @param space the choosen space of the target
  18862. * @returns the TransformNode.
  18863. */
  18864. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18865. if (yawCor === void 0) { yawCor = 0; }
  18866. if (pitchCor === void 0) { pitchCor = 0; }
  18867. if (rollCor === void 0) { rollCor = 0; }
  18868. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18869. var dv = TransformNode._lookAtVectorCache;
  18870. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18871. targetPoint.subtractToRef(pos, dv);
  18872. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18873. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18874. var pitch = Math.atan2(dv.y, len);
  18875. if (this.rotationQuaternion) {
  18876. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18877. }
  18878. else {
  18879. this.rotation.x = pitch + pitchCor;
  18880. this.rotation.y = yaw + yawCor;
  18881. this.rotation.z = rollCor;
  18882. }
  18883. return this;
  18884. };
  18885. /**
  18886. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18887. * This Vector3 is expressed in the World space.
  18888. */
  18889. TransformNode.prototype.getDirection = function (localAxis) {
  18890. var result = BABYLON.Vector3.Zero();
  18891. this.getDirectionToRef(localAxis, result);
  18892. return result;
  18893. };
  18894. /**
  18895. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18896. * localAxis is expressed in the mesh local space.
  18897. * result is computed in the Wordl space from the mesh World matrix.
  18898. * Returns the TransformNode.
  18899. */
  18900. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18901. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18902. return this;
  18903. };
  18904. /**
  18905. * Sets a new pivot point to the current node
  18906. * @param point defines the new pivot point to use
  18907. * @param space defines if the point is in world or local space (local by default)
  18908. * @returns the current TransformNode
  18909. */
  18910. TransformNode.prototype.setPivotPoint = function (point, space) {
  18911. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18912. if (this.getScene().getRenderId() == 0) {
  18913. this.computeWorldMatrix(true);
  18914. }
  18915. var wm = this.getWorldMatrix();
  18916. if (space == BABYLON.Space.WORLD) {
  18917. var tmat = BABYLON.Tmp.Matrix[0];
  18918. wm.invertToRef(tmat);
  18919. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18920. }
  18921. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18922. };
  18923. /**
  18924. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18925. */
  18926. TransformNode.prototype.getPivotPoint = function () {
  18927. var point = BABYLON.Vector3.Zero();
  18928. this.getPivotPointToRef(point);
  18929. return point;
  18930. };
  18931. /**
  18932. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18933. * Returns the TransformNode.
  18934. */
  18935. TransformNode.prototype.getPivotPointToRef = function (result) {
  18936. result.x = -this._pivotMatrix.m[12];
  18937. result.y = -this._pivotMatrix.m[13];
  18938. result.z = -this._pivotMatrix.m[14];
  18939. return this;
  18940. };
  18941. /**
  18942. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18943. */
  18944. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18945. var point = BABYLON.Vector3.Zero();
  18946. this.getAbsolutePivotPointToRef(point);
  18947. return point;
  18948. };
  18949. /**
  18950. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18951. * Returns the TransformNode.
  18952. */
  18953. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18954. result.x = this._pivotMatrix.m[12];
  18955. result.y = this._pivotMatrix.m[13];
  18956. result.z = this._pivotMatrix.m[14];
  18957. this.getPivotPointToRef(result);
  18958. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18959. return this;
  18960. };
  18961. /**
  18962. * Defines the passed node as the parent of the current node.
  18963. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18964. * Returns the TransformNode.
  18965. */
  18966. TransformNode.prototype.setParent = function (node) {
  18967. if (node === null) {
  18968. var rotation = BABYLON.Tmp.Quaternion[0];
  18969. var position = BABYLON.Tmp.Vector3[0];
  18970. var scale = BABYLON.Tmp.Vector3[1];
  18971. if (this.parent && this.parent.computeWorldMatrix) {
  18972. this.parent.computeWorldMatrix(true);
  18973. }
  18974. this.computeWorldMatrix(true);
  18975. this.getWorldMatrix().decompose(scale, rotation, position);
  18976. if (this.rotationQuaternion) {
  18977. this.rotationQuaternion.copyFrom(rotation);
  18978. }
  18979. else {
  18980. rotation.toEulerAnglesToRef(this.rotation);
  18981. }
  18982. this.scaling.x = scale.x;
  18983. this.scaling.y = scale.y;
  18984. this.scaling.z = scale.z;
  18985. this.position.x = position.x;
  18986. this.position.y = position.y;
  18987. this.position.z = position.z;
  18988. }
  18989. else {
  18990. var rotation = BABYLON.Tmp.Quaternion[0];
  18991. var position = BABYLON.Tmp.Vector3[0];
  18992. var scale = BABYLON.Tmp.Vector3[1];
  18993. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18994. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18995. this.computeWorldMatrix(true);
  18996. node.computeWorldMatrix(true);
  18997. node.getWorldMatrix().invertToRef(invParentMatrix);
  18998. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18999. diffMatrix.decompose(scale, rotation, position);
  19000. if (this.rotationQuaternion) {
  19001. this.rotationQuaternion.copyFrom(rotation);
  19002. }
  19003. else {
  19004. rotation.toEulerAnglesToRef(this.rotation);
  19005. }
  19006. this.position.x = position.x;
  19007. this.position.y = position.y;
  19008. this.position.z = position.z;
  19009. this.scaling.x = scale.x;
  19010. this.scaling.y = scale.y;
  19011. this.scaling.z = scale.z;
  19012. }
  19013. this.parent = node;
  19014. return this;
  19015. };
  19016. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19017. get: function () {
  19018. return this._nonUniformScaling;
  19019. },
  19020. enumerable: true,
  19021. configurable: true
  19022. });
  19023. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19024. if (this._nonUniformScaling === value) {
  19025. return false;
  19026. }
  19027. this._nonUniformScaling = value;
  19028. return true;
  19029. };
  19030. /**
  19031. * Attach the current TransformNode to another TransformNode associated with a bone
  19032. * @param bone Bone affecting the TransformNode
  19033. * @param affectedTransformNode TransformNode associated with the bone
  19034. */
  19035. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19036. this._transformToBoneReferal = affectedTransformNode;
  19037. this.parent = bone;
  19038. if (bone.getWorldMatrix().determinant() < 0) {
  19039. this.scalingDeterminant *= -1;
  19040. }
  19041. return this;
  19042. };
  19043. TransformNode.prototype.detachFromBone = function () {
  19044. if (!this.parent) {
  19045. return this;
  19046. }
  19047. if (this.parent.getWorldMatrix().determinant() < 0) {
  19048. this.scalingDeterminant *= -1;
  19049. }
  19050. this._transformToBoneReferal = null;
  19051. this.parent = null;
  19052. return this;
  19053. };
  19054. /**
  19055. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19056. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19057. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19058. * The passed axis is also normalized.
  19059. * Returns the TransformNode.
  19060. */
  19061. TransformNode.prototype.rotate = function (axis, amount, space) {
  19062. axis.normalize();
  19063. if (!this.rotationQuaternion) {
  19064. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19065. this.rotation = BABYLON.Vector3.Zero();
  19066. }
  19067. var rotationQuaternion;
  19068. if (!space || space === BABYLON.Space.LOCAL) {
  19069. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19070. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19071. }
  19072. else {
  19073. if (this.parent) {
  19074. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19075. invertParentWorldMatrix.invert();
  19076. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19077. }
  19078. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19079. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19080. }
  19081. return this;
  19082. };
  19083. /**
  19084. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19085. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19086. * The passed axis is also normalized.
  19087. * Returns the TransformNode.
  19088. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19089. */
  19090. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19091. axis.normalize();
  19092. if (!this.rotationQuaternion) {
  19093. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19094. this.rotation.copyFromFloats(0, 0, 0);
  19095. }
  19096. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19097. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19098. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19099. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19100. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19101. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19102. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19103. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19104. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19105. return this;
  19106. };
  19107. /**
  19108. * Translates the mesh along the axis vector for the passed distance in the given space.
  19109. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19110. * Returns the TransformNode.
  19111. */
  19112. TransformNode.prototype.translate = function (axis, distance, space) {
  19113. var displacementVector = axis.scale(distance);
  19114. if (!space || space === BABYLON.Space.LOCAL) {
  19115. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19116. this.setPositionWithLocalVector(tempV3);
  19117. }
  19118. else {
  19119. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19120. }
  19121. return this;
  19122. };
  19123. /**
  19124. * Adds a rotation step to the mesh current rotation.
  19125. * x, y, z are Euler angles expressed in radians.
  19126. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19127. * This means this rotation is made in the mesh local space only.
  19128. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19129. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19130. * ```javascript
  19131. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19132. * ```
  19133. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19134. * 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.
  19135. * Returns the TransformNode.
  19136. */
  19137. TransformNode.prototype.addRotation = function (x, y, z) {
  19138. var rotationQuaternion;
  19139. if (this.rotationQuaternion) {
  19140. rotationQuaternion = this.rotationQuaternion;
  19141. }
  19142. else {
  19143. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19144. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19145. }
  19146. var accumulation = BABYLON.Tmp.Quaternion[0];
  19147. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19148. rotationQuaternion.multiplyInPlace(accumulation);
  19149. if (!this.rotationQuaternion) {
  19150. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19151. }
  19152. return this;
  19153. };
  19154. /**
  19155. * Computes the mesh World matrix and returns it.
  19156. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19157. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19158. * If the parameter `force`is set to `true`, the actual computation is done.
  19159. * Returns the mesh World Matrix.
  19160. */
  19161. TransformNode.prototype.computeWorldMatrix = function (force) {
  19162. if (this._isWorldMatrixFrozen) {
  19163. return this._worldMatrix;
  19164. }
  19165. if (!force && this.isSynchronized(true)) {
  19166. this._currentRenderId = this.getScene().getRenderId();
  19167. return this._worldMatrix;
  19168. }
  19169. this._cache.position.copyFrom(this.position);
  19170. this._cache.scaling.copyFrom(this.scaling);
  19171. this._cache.pivotMatrixUpdated = false;
  19172. this._cache.billboardMode = this.billboardMode;
  19173. this._currentRenderId = this.getScene().getRenderId();
  19174. this._childRenderId = this.getScene().getRenderId();
  19175. this._isDirty = false;
  19176. // Scaling
  19177. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19178. // Rotation
  19179. //rotate, if quaternion is set and rotation was used
  19180. if (this.rotationQuaternion) {
  19181. var len = this.rotation.length();
  19182. if (len) {
  19183. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19184. this.rotation.copyFromFloats(0, 0, 0);
  19185. }
  19186. }
  19187. if (this.rotationQuaternion) {
  19188. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19189. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19190. }
  19191. else {
  19192. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19193. this._cache.rotation.copyFrom(this.rotation);
  19194. }
  19195. // Translation
  19196. var camera = this.getScene().activeCamera;
  19197. if (this.infiniteDistance && !this.parent && camera) {
  19198. var cameraWorldMatrix = camera.getWorldMatrix();
  19199. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19200. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19201. }
  19202. else {
  19203. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19204. }
  19205. // Composing transformations
  19206. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19207. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19208. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19209. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19210. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19211. // Need to decompose each rotation here
  19212. var currentPosition = BABYLON.Tmp.Vector3[3];
  19213. if (this.parent && this.parent.getWorldMatrix) {
  19214. if (this._transformToBoneReferal) {
  19215. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19216. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19217. }
  19218. else {
  19219. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19220. }
  19221. }
  19222. else {
  19223. currentPosition.copyFrom(this.position);
  19224. }
  19225. currentPosition.subtractInPlace(camera.globalPosition);
  19226. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19227. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19228. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19229. }
  19230. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19231. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19232. }
  19233. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19234. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19235. }
  19236. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19237. }
  19238. else {
  19239. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19240. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19241. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19242. }
  19243. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19244. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19245. }
  19246. // Local world
  19247. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19248. // Parent
  19249. if (this.parent && this.parent.getWorldMatrix) {
  19250. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19251. if (this._transformToBoneReferal) {
  19252. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19253. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19254. }
  19255. else {
  19256. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19257. }
  19258. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19259. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19260. this._worldMatrix.copyFrom(this._localWorld);
  19261. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19262. }
  19263. else {
  19264. if (this._transformToBoneReferal) {
  19265. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19266. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19267. }
  19268. else {
  19269. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19270. }
  19271. }
  19272. this._markSyncedWithParent();
  19273. }
  19274. else {
  19275. this._worldMatrix.copyFrom(this._localWorld);
  19276. }
  19277. // Post multiply inverse of pivotMatrix
  19278. if (this._postMultiplyPivotMatrix) {
  19279. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19280. }
  19281. // Normal matrix
  19282. if (!this.ignoreNonUniformScaling) {
  19283. if (this.scaling.isNonUniform) {
  19284. this._updateNonUniformScalingState(true);
  19285. }
  19286. else if (this.parent && this.parent._nonUniformScaling) {
  19287. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19288. }
  19289. else {
  19290. this._updateNonUniformScalingState(false);
  19291. }
  19292. }
  19293. else {
  19294. this._updateNonUniformScalingState(false);
  19295. }
  19296. this._afterComputeWorldMatrix();
  19297. // Absolute position
  19298. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19299. // Callbacks
  19300. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19301. if (!this._poseMatrix) {
  19302. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19303. }
  19304. // Cache the determinant
  19305. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19306. return this._worldMatrix;
  19307. };
  19308. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19309. };
  19310. /**
  19311. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19312. * @param func: callback function to add
  19313. *
  19314. * Returns the TransformNode.
  19315. */
  19316. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19317. this.onAfterWorldMatrixUpdateObservable.add(func);
  19318. return this;
  19319. };
  19320. /**
  19321. * Removes a registered callback function.
  19322. * Returns the TransformNode.
  19323. */
  19324. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19325. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19326. return this;
  19327. };
  19328. /**
  19329. * Clone the current transform node
  19330. * Returns the new transform node
  19331. * @param name Name of the new clone
  19332. * @param newParent New parent for the clone
  19333. * @param doNotCloneChildren Do not clone children hierarchy
  19334. */
  19335. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19336. var _this = this;
  19337. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19338. result.name = name;
  19339. result.id = name;
  19340. if (newParent) {
  19341. result.parent = newParent;
  19342. }
  19343. if (!doNotCloneChildren) {
  19344. // Children
  19345. var directDescendants = this.getDescendants(true);
  19346. for (var index = 0; index < directDescendants.length; index++) {
  19347. var child = directDescendants[index];
  19348. if (child.clone) {
  19349. child.clone(name + "." + child.name, result);
  19350. }
  19351. }
  19352. }
  19353. return result;
  19354. };
  19355. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19356. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19357. serializationObject.type = this.getClassName();
  19358. // Parent
  19359. if (this.parent) {
  19360. serializationObject.parentId = this.parent.id;
  19361. }
  19362. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19363. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19364. }
  19365. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19366. serializationObject.isEnabled = this.isEnabled();
  19367. // Parent
  19368. if (this.parent) {
  19369. serializationObject.parentId = this.parent.id;
  19370. }
  19371. return serializationObject;
  19372. };
  19373. // Statics
  19374. /**
  19375. * Returns a new TransformNode object parsed from the source provided.
  19376. * The parameter `parsedMesh` is the source.
  19377. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19378. */
  19379. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19380. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19381. if (BABYLON.Tags) {
  19382. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19383. }
  19384. if (parsedTransformNode.localMatrix) {
  19385. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19386. }
  19387. else if (parsedTransformNode.pivotMatrix) {
  19388. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19389. }
  19390. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19391. // Parent
  19392. if (parsedTransformNode.parentId) {
  19393. transformNode._waitingParentId = parsedTransformNode.parentId;
  19394. }
  19395. return transformNode;
  19396. };
  19397. /**
  19398. * Releases resources associated with this transform node.
  19399. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19400. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19401. */
  19402. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19403. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19404. // Animations
  19405. this.getScene().stopAnimation(this);
  19406. // Remove from scene
  19407. this.getScene().removeTransformNode(this);
  19408. this.onAfterWorldMatrixUpdateObservable.clear();
  19409. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19410. };
  19411. // Statics
  19412. TransformNode.BILLBOARDMODE_NONE = 0;
  19413. TransformNode.BILLBOARDMODE_X = 1;
  19414. TransformNode.BILLBOARDMODE_Y = 2;
  19415. TransformNode.BILLBOARDMODE_Z = 4;
  19416. TransformNode.BILLBOARDMODE_ALL = 7;
  19417. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19418. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19419. __decorate([
  19420. BABYLON.serializeAsVector3()
  19421. ], TransformNode.prototype, "_rotation", void 0);
  19422. __decorate([
  19423. BABYLON.serializeAsQuaternion()
  19424. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19425. __decorate([
  19426. BABYLON.serializeAsVector3()
  19427. ], TransformNode.prototype, "_scaling", void 0);
  19428. __decorate([
  19429. BABYLON.serialize()
  19430. ], TransformNode.prototype, "billboardMode", void 0);
  19431. __decorate([
  19432. BABYLON.serialize()
  19433. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19434. __decorate([
  19435. BABYLON.serialize()
  19436. ], TransformNode.prototype, "infiniteDistance", void 0);
  19437. __decorate([
  19438. BABYLON.serialize()
  19439. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19440. __decorate([
  19441. BABYLON.serializeAsVector3()
  19442. ], TransformNode.prototype, "position", void 0);
  19443. return TransformNode;
  19444. }(BABYLON.Node));
  19445. BABYLON.TransformNode = TransformNode;
  19446. })(BABYLON || (BABYLON = {}));
  19447. //# sourceMappingURL=babylon.transformNode.js.map
  19448. var BABYLON;
  19449. (function (BABYLON) {
  19450. /**
  19451. * Class used to store all common mesh properties
  19452. */
  19453. var AbstractMesh = /** @class */ (function (_super) {
  19454. __extends(AbstractMesh, _super);
  19455. // Constructor
  19456. /**
  19457. * Creates a new AbstractMesh
  19458. * @param name defines the name of the mesh
  19459. * @param scene defines the hosting scene
  19460. */
  19461. function AbstractMesh(name, scene) {
  19462. if (scene === void 0) { scene = null; }
  19463. var _this = _super.call(this, name, scene, false) || this;
  19464. _this._facetNb = 0; // facet number
  19465. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19466. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19467. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19468. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19469. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19470. _this._subDiv = {
  19471. max: 1,
  19472. X: 1,
  19473. Y: 1,
  19474. Z: 1
  19475. };
  19476. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19477. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19478. // Events
  19479. /**
  19480. * An event triggered when this mesh collides with another one
  19481. */
  19482. _this.onCollideObservable = new BABYLON.Observable();
  19483. /**
  19484. * An event triggered when the collision's position changes
  19485. */
  19486. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19487. /**
  19488. * An event triggered when material is changed
  19489. */
  19490. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19491. // Properties
  19492. /**
  19493. * Gets or sets the orientation for POV movement & rotation
  19494. */
  19495. _this.definedFacingForward = true;
  19496. /**
  19497. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19498. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19499. * * 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.
  19500. * @see http://doc.babylonjs.com/features/occlusionquery
  19501. */
  19502. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19503. /**
  19504. * 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:
  19505. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19506. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19507. * * 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.
  19508. * @see http://doc.babylonjs.com/features/occlusionquery
  19509. */
  19510. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19511. /**
  19512. * 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.
  19513. * The default value is -1 which means don't break the query and wait till the result
  19514. * @see http://doc.babylonjs.com/features/occlusionquery
  19515. */
  19516. _this.occlusionRetryCount = -1;
  19517. _this._occlusionInternalRetryCounter = 0;
  19518. _this._isOccluded = false;
  19519. _this._isOcclusionQueryInProgress = false;
  19520. _this._visibility = 1.0;
  19521. /** Gets or sets the alpha index used to sort transparent meshes
  19522. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19523. */
  19524. _this.alphaIndex = Number.MAX_VALUE;
  19525. /**
  19526. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19527. */
  19528. _this.isVisible = true;
  19529. /**
  19530. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19531. */
  19532. _this.isPickable = true;
  19533. /**
  19534. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19535. */
  19536. _this.showBoundingBox = false;
  19537. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19538. _this.showSubMeshesBoundingBox = false;
  19539. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19540. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19541. */
  19542. _this.isBlocker = false;
  19543. /**
  19544. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19545. */
  19546. _this.enablePointerMoveEvents = false;
  19547. /**
  19548. * Specifies the rendering group id for this mesh (0 by default)
  19549. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19550. */
  19551. _this.renderingGroupId = 0;
  19552. _this._receiveShadows = false;
  19553. /**
  19554. * Gets or sets a boolean indicating if the outline must be rendered as well
  19555. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19556. */
  19557. _this.renderOutline = false;
  19558. /** Defines color to use when rendering outline */
  19559. _this.outlineColor = BABYLON.Color3.Red();
  19560. /** Define width to use when rendering outline */
  19561. _this.outlineWidth = 0.02;
  19562. /**
  19563. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19564. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19565. */
  19566. _this.renderOverlay = false;
  19567. /** Defines color to use when rendering overlay */
  19568. _this.overlayColor = BABYLON.Color3.Red();
  19569. /** Defines alpha to use when rendering overlay */
  19570. _this.overlayAlpha = 0.5;
  19571. _this._hasVertexAlpha = false;
  19572. _this._useVertexColors = true;
  19573. _this._computeBonesUsingShaders = true;
  19574. _this._numBoneInfluencers = 4;
  19575. _this._applyFog = true;
  19576. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19577. _this.useOctreeForRenderingSelection = true;
  19578. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19579. _this.useOctreeForPicking = true;
  19580. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19581. _this.useOctreeForCollisions = true;
  19582. _this._layerMask = 0x0FFFFFFF;
  19583. /**
  19584. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19585. */
  19586. _this.alwaysSelectAsActiveMesh = false;
  19587. /**
  19588. * Gets or sets the current action manager
  19589. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19590. */
  19591. _this.actionManager = null;
  19592. /**
  19593. * Gets or sets impostor used for physic simulation
  19594. * @see http://doc.babylonjs.com/features/physics_engine
  19595. */
  19596. _this.physicsImpostor = null;
  19597. // Collisions
  19598. _this._checkCollisions = false;
  19599. _this._collisionMask = -1;
  19600. _this._collisionGroup = -1;
  19601. /**
  19602. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19603. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19604. */
  19605. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19606. /**
  19607. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19608. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19609. */
  19610. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19611. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19612. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19613. // Edges
  19614. /**
  19615. * Defines edge width used when edgesRenderer is enabled
  19616. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19617. */
  19618. _this.edgesWidth = 1;
  19619. /**
  19620. * Defines edge color used when edgesRenderer is enabled
  19621. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19622. */
  19623. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19624. // Cache
  19625. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19626. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19627. /** @hidden */
  19628. _this._renderId = 0;
  19629. /** @hidden */
  19630. _this._intersectionsInProgress = new Array();
  19631. /** @hidden */
  19632. _this._unIndexed = false;
  19633. /** @hidden */
  19634. _this._lightSources = new Array();
  19635. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19636. if (collidedMesh === void 0) { collidedMesh = null; }
  19637. //TODO move this to the collision coordinator!
  19638. if (_this.getScene().workerCollisions)
  19639. newPosition.multiplyInPlace(_this._collider._radius);
  19640. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19641. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19642. _this.position.addInPlace(_this._diffPositionForCollisions);
  19643. }
  19644. if (collidedMesh) {
  19645. _this.onCollideObservable.notifyObservers(collidedMesh);
  19646. }
  19647. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19648. };
  19649. _this.getScene().addMesh(_this);
  19650. _this._resyncLightSources();
  19651. return _this;
  19652. }
  19653. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19654. /**
  19655. * No billboard
  19656. */
  19657. get: function () {
  19658. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19659. },
  19660. enumerable: true,
  19661. configurable: true
  19662. });
  19663. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19664. /** Billboard on X axis */
  19665. get: function () {
  19666. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19667. },
  19668. enumerable: true,
  19669. configurable: true
  19670. });
  19671. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19672. /** Billboard on Y axis */
  19673. get: function () {
  19674. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19680. /** Billboard on Z axis */
  19681. get: function () {
  19682. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19683. },
  19684. enumerable: true,
  19685. configurable: true
  19686. });
  19687. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19688. /** Billboard on all axes */
  19689. get: function () {
  19690. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19691. },
  19692. enumerable: true,
  19693. configurable: true
  19694. });
  19695. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19696. /**
  19697. * Gets the number of facets in the mesh
  19698. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19699. */
  19700. get: function () {
  19701. return this._facetNb;
  19702. },
  19703. enumerable: true,
  19704. configurable: true
  19705. });
  19706. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19707. /**
  19708. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19709. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19710. */
  19711. get: function () {
  19712. return this._partitioningSubdivisions;
  19713. },
  19714. set: function (nb) {
  19715. this._partitioningSubdivisions = nb;
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19721. /**
  19722. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19723. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19724. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19725. */
  19726. get: function () {
  19727. return this._partitioningBBoxRatio;
  19728. },
  19729. set: function (ratio) {
  19730. this._partitioningBBoxRatio = ratio;
  19731. },
  19732. enumerable: true,
  19733. configurable: true
  19734. });
  19735. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19736. /**
  19737. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19738. * Works only for updatable meshes.
  19739. * Doesn't work with multi-materials
  19740. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19741. */
  19742. get: function () {
  19743. return this._facetDepthSort;
  19744. },
  19745. set: function (sort) {
  19746. this._facetDepthSort = sort;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19752. /**
  19753. * The location (Vector3) where the facet depth sort must be computed from.
  19754. * By default, the active camera position.
  19755. * Used only when facet depth sort is enabled
  19756. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19757. */
  19758. get: function () {
  19759. return this._facetDepthSortFrom;
  19760. },
  19761. set: function (location) {
  19762. this._facetDepthSortFrom = location;
  19763. },
  19764. enumerable: true,
  19765. configurable: true
  19766. });
  19767. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19768. /**
  19769. * gets a boolean indicating if facetData is enabled
  19770. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19771. */
  19772. get: function () {
  19773. return this._facetDataEnabled;
  19774. },
  19775. enumerable: true,
  19776. configurable: true
  19777. });
  19778. /** @hidden */
  19779. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19780. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19781. return false;
  19782. }
  19783. this._markSubMeshesAsMiscDirty();
  19784. return true;
  19785. };
  19786. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19787. /** Set a function to call when this mesh collides with another one */
  19788. set: function (callback) {
  19789. if (this._onCollideObserver) {
  19790. this.onCollideObservable.remove(this._onCollideObserver);
  19791. }
  19792. this._onCollideObserver = this.onCollideObservable.add(callback);
  19793. },
  19794. enumerable: true,
  19795. configurable: true
  19796. });
  19797. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19798. /** Set a function to call when the collision's position changes */
  19799. set: function (callback) {
  19800. if (this._onCollisionPositionChangeObserver) {
  19801. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19802. }
  19803. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19809. /**
  19810. * 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
  19811. * @see http://doc.babylonjs.com/features/occlusionquery
  19812. */
  19813. get: function () {
  19814. return this._isOccluded;
  19815. },
  19816. set: function (value) {
  19817. this._isOccluded = value;
  19818. },
  19819. enumerable: true,
  19820. configurable: true
  19821. });
  19822. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19823. /**
  19824. * Flag to check the progress status of the query
  19825. * @see http://doc.babylonjs.com/features/occlusionquery
  19826. */
  19827. get: function () {
  19828. return this._isOcclusionQueryInProgress;
  19829. },
  19830. enumerable: true,
  19831. configurable: true
  19832. });
  19833. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19834. /**
  19835. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19836. */
  19837. get: function () {
  19838. return this._visibility;
  19839. },
  19840. /**
  19841. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19842. */
  19843. set: function (value) {
  19844. if (this._visibility === value) {
  19845. return;
  19846. }
  19847. this._visibility = value;
  19848. this._markSubMeshesAsMiscDirty();
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Object.defineProperty(AbstractMesh.prototype, "material", {
  19854. /** Gets or sets current material */
  19855. get: function () {
  19856. return this._material;
  19857. },
  19858. set: function (value) {
  19859. if (this._material === value) {
  19860. return;
  19861. }
  19862. this._material = value;
  19863. if (this.onMaterialChangedObservable.hasObservers) {
  19864. this.onMaterialChangedObservable.notifyObservers(this);
  19865. }
  19866. if (!this.subMeshes) {
  19867. return;
  19868. }
  19869. this._unBindEffect();
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19875. /**
  19876. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19877. * @see http://doc.babylonjs.com/babylon101/shadows
  19878. */
  19879. get: function () {
  19880. return this._receiveShadows;
  19881. },
  19882. set: function (value) {
  19883. if (this._receiveShadows === value) {
  19884. return;
  19885. }
  19886. this._receiveShadows = value;
  19887. this._markSubMeshesAsLightDirty();
  19888. },
  19889. enumerable: true,
  19890. configurable: true
  19891. });
  19892. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19893. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19894. get: function () {
  19895. return this._hasVertexAlpha;
  19896. },
  19897. set: function (value) {
  19898. if (this._hasVertexAlpha === value) {
  19899. return;
  19900. }
  19901. this._hasVertexAlpha = value;
  19902. this._markSubMeshesAsAttributesDirty();
  19903. this._markSubMeshesAsMiscDirty();
  19904. },
  19905. enumerable: true,
  19906. configurable: true
  19907. });
  19908. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19909. /** 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) */
  19910. get: function () {
  19911. return this._useVertexColors;
  19912. },
  19913. set: function (value) {
  19914. if (this._useVertexColors === value) {
  19915. return;
  19916. }
  19917. this._useVertexColors = value;
  19918. this._markSubMeshesAsAttributesDirty();
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19924. /**
  19925. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19926. */
  19927. get: function () {
  19928. return this._computeBonesUsingShaders;
  19929. },
  19930. set: function (value) {
  19931. if (this._computeBonesUsingShaders === value) {
  19932. return;
  19933. }
  19934. this._computeBonesUsingShaders = value;
  19935. this._markSubMeshesAsAttributesDirty();
  19936. },
  19937. enumerable: true,
  19938. configurable: true
  19939. });
  19940. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19941. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19942. get: function () {
  19943. return this._numBoneInfluencers;
  19944. },
  19945. set: function (value) {
  19946. if (this._numBoneInfluencers === value) {
  19947. return;
  19948. }
  19949. this._numBoneInfluencers = value;
  19950. this._markSubMeshesAsAttributesDirty();
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19956. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19957. get: function () {
  19958. return this._applyFog;
  19959. },
  19960. set: function (value) {
  19961. if (this._applyFog === value) {
  19962. return;
  19963. }
  19964. this._applyFog = value;
  19965. this._markSubMeshesAsMiscDirty();
  19966. },
  19967. enumerable: true,
  19968. configurable: true
  19969. });
  19970. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19971. /**
  19972. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19973. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19974. */
  19975. get: function () {
  19976. return this._layerMask;
  19977. },
  19978. set: function (value) {
  19979. if (value === this._layerMask) {
  19980. return;
  19981. }
  19982. this._layerMask = value;
  19983. this._resyncLightSources();
  19984. },
  19985. enumerable: true,
  19986. configurable: true
  19987. });
  19988. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19989. /**
  19990. * Gets or sets a collision mask used to mask collisions (default is -1).
  19991. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19992. */
  19993. get: function () {
  19994. return this._collisionMask;
  19995. },
  19996. set: function (mask) {
  19997. this._collisionMask = !isNaN(mask) ? mask : -1;
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20003. /**
  20004. * Gets or sets the current collision group mask (-1 by default).
  20005. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20006. */
  20007. get: function () {
  20008. return this._collisionGroup;
  20009. },
  20010. set: function (mask) {
  20011. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20012. },
  20013. enumerable: true,
  20014. configurable: true
  20015. });
  20016. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20017. /** @hidden */
  20018. get: function () {
  20019. return null;
  20020. },
  20021. enumerable: true,
  20022. configurable: true
  20023. });
  20024. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20025. get: function () {
  20026. return this._skeleton;
  20027. },
  20028. /**
  20029. * Gets or sets a skeleton to apply skining transformations
  20030. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20031. */
  20032. set: function (value) {
  20033. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20034. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20035. }
  20036. if (value && value.needInitialSkinMatrix) {
  20037. value._registerMeshWithPoseMatrix(this);
  20038. }
  20039. this._skeleton = value;
  20040. if (!this._skeleton) {
  20041. this._bonesTransformMatrices = null;
  20042. }
  20043. this._markSubMeshesAsAttributesDirty();
  20044. },
  20045. enumerable: true,
  20046. configurable: true
  20047. });
  20048. /**
  20049. * Returns the string "AbstractMesh"
  20050. * @returns "AbstractMesh"
  20051. */
  20052. AbstractMesh.prototype.getClassName = function () {
  20053. return "AbstractMesh";
  20054. };
  20055. /**
  20056. * Gets a string representation of the current mesh
  20057. * @param fullDetails defines a boolean indicating if full details must be included
  20058. * @returns a string representation of the current mesh
  20059. */
  20060. AbstractMesh.prototype.toString = function (fullDetails) {
  20061. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20062. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20063. if (this._skeleton) {
  20064. ret += ", skeleton: " + this._skeleton.name;
  20065. }
  20066. if (fullDetails) {
  20067. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20068. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20069. }
  20070. return ret;
  20071. };
  20072. /** @hidden */
  20073. AbstractMesh.prototype._rebuild = function () {
  20074. if (this._occlusionQuery) {
  20075. this._occlusionQuery = null;
  20076. }
  20077. if (this._edgesRenderer) {
  20078. this._edgesRenderer._rebuild();
  20079. }
  20080. if (!this.subMeshes) {
  20081. return;
  20082. }
  20083. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20084. var subMesh = _a[_i];
  20085. subMesh._rebuild();
  20086. }
  20087. };
  20088. /** @hidden */
  20089. AbstractMesh.prototype._resyncLightSources = function () {
  20090. this._lightSources.length = 0;
  20091. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20092. var light = _a[_i];
  20093. if (!light.isEnabled()) {
  20094. continue;
  20095. }
  20096. if (light.canAffectMesh(this)) {
  20097. this._lightSources.push(light);
  20098. }
  20099. }
  20100. this._markSubMeshesAsLightDirty();
  20101. };
  20102. /** @hidden */
  20103. AbstractMesh.prototype._resyncLighSource = function (light) {
  20104. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20105. var index = this._lightSources.indexOf(light);
  20106. if (index === -1) {
  20107. if (!isIn) {
  20108. return;
  20109. }
  20110. this._lightSources.push(light);
  20111. }
  20112. else {
  20113. if (isIn) {
  20114. return;
  20115. }
  20116. this._lightSources.splice(index, 1);
  20117. }
  20118. this._markSubMeshesAsLightDirty();
  20119. };
  20120. /** @hidden */
  20121. AbstractMesh.prototype._unBindEffect = function () {
  20122. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20123. var subMesh = _a[_i];
  20124. subMesh.setEffect(null);
  20125. }
  20126. };
  20127. /** @hidden */
  20128. AbstractMesh.prototype._removeLightSource = function (light) {
  20129. var index = this._lightSources.indexOf(light);
  20130. if (index === -1) {
  20131. return;
  20132. }
  20133. this._lightSources.splice(index, 1);
  20134. this._markSubMeshesAsLightDirty();
  20135. };
  20136. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20137. if (!this.subMeshes) {
  20138. return;
  20139. }
  20140. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20141. var subMesh = _a[_i];
  20142. if (subMesh._materialDefines) {
  20143. func(subMesh._materialDefines);
  20144. }
  20145. }
  20146. };
  20147. /** @hidden */
  20148. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20149. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20150. };
  20151. /** @hidden */
  20152. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20153. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20154. };
  20155. /** @hidden */
  20156. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20157. if (!this.subMeshes) {
  20158. return;
  20159. }
  20160. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20161. var subMesh = _a[_i];
  20162. var material = subMesh.getMaterial();
  20163. if (material) {
  20164. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20165. }
  20166. }
  20167. };
  20168. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20169. /**
  20170. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20171. */
  20172. get: function () {
  20173. return this._scaling;
  20174. },
  20175. set: function (newScaling) {
  20176. this._scaling = newScaling;
  20177. if (this.physicsImpostor) {
  20178. this.physicsImpostor.forceUpdate();
  20179. }
  20180. },
  20181. enumerable: true,
  20182. configurable: true
  20183. });
  20184. // Methods
  20185. /**
  20186. * Disables the mesh edge rendering mode
  20187. * @returns the currentAbstractMesh
  20188. */
  20189. AbstractMesh.prototype.disableEdgesRendering = function () {
  20190. if (this._edgesRenderer) {
  20191. this._edgesRenderer.dispose();
  20192. this._edgesRenderer = null;
  20193. }
  20194. return this;
  20195. };
  20196. /**
  20197. * Enables the edge rendering mode on the mesh.
  20198. * This mode makes the mesh edges visible
  20199. * @param epsilon defines the maximal distance between two angles to detect a face
  20200. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20201. * @returns the currentAbstractMesh
  20202. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20203. */
  20204. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20205. if (epsilon === void 0) { epsilon = 0.95; }
  20206. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20207. this.disableEdgesRendering();
  20208. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20209. return this;
  20210. };
  20211. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20212. /**
  20213. * Gets the edgesRenderer associated with the mesh
  20214. */
  20215. get: function () {
  20216. return this._edgesRenderer;
  20217. },
  20218. enumerable: true,
  20219. configurable: true
  20220. });
  20221. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20222. /**
  20223. * Returns true if the mesh is blocked. Implemented by child classes
  20224. */
  20225. get: function () {
  20226. return false;
  20227. },
  20228. enumerable: true,
  20229. configurable: true
  20230. });
  20231. /**
  20232. * Returns the mesh itself by default. Implemented by child classes
  20233. * @param camera defines the camera to use to pick the right LOD level
  20234. * @returns the currentAbstractMesh
  20235. */
  20236. AbstractMesh.prototype.getLOD = function (camera) {
  20237. return this;
  20238. };
  20239. /**
  20240. * Returns 0 by default. Implemented by child classes
  20241. * @returns an integer
  20242. */
  20243. AbstractMesh.prototype.getTotalVertices = function () {
  20244. return 0;
  20245. };
  20246. /**
  20247. * Returns null by default. Implemented by child classes
  20248. * @returns null
  20249. */
  20250. AbstractMesh.prototype.getIndices = function () {
  20251. return null;
  20252. };
  20253. /**
  20254. * Returns the array of the requested vertex data kind. Implemented by child classes
  20255. * @param kind defines the vertex data kind to use
  20256. * @returns null
  20257. */
  20258. AbstractMesh.prototype.getVerticesData = function (kind) {
  20259. return null;
  20260. };
  20261. /**
  20262. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20263. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20264. * Note that a new underlying VertexBuffer object is created each call.
  20265. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20266. * @param kind defines vertex data kind:
  20267. * * BABYLON.VertexBuffer.PositionKind
  20268. * * BABYLON.VertexBuffer.UVKind
  20269. * * BABYLON.VertexBuffer.UV2Kind
  20270. * * BABYLON.VertexBuffer.UV3Kind
  20271. * * BABYLON.VertexBuffer.UV4Kind
  20272. * * BABYLON.VertexBuffer.UV5Kind
  20273. * * BABYLON.VertexBuffer.UV6Kind
  20274. * * BABYLON.VertexBuffer.ColorKind
  20275. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20276. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20277. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20278. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20279. * @param data defines the data source
  20280. * @param updatable defines if the data must be flagged as updatable (or static)
  20281. * @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
  20282. * @returns the current mesh
  20283. */
  20284. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20285. return this;
  20286. };
  20287. /**
  20288. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20289. * If the mesh has no geometry, it is simply returned as it is.
  20290. * @param kind defines vertex data kind:
  20291. * * BABYLON.VertexBuffer.PositionKind
  20292. * * BABYLON.VertexBuffer.UVKind
  20293. * * BABYLON.VertexBuffer.UV2Kind
  20294. * * BABYLON.VertexBuffer.UV3Kind
  20295. * * BABYLON.VertexBuffer.UV4Kind
  20296. * * BABYLON.VertexBuffer.UV5Kind
  20297. * * BABYLON.VertexBuffer.UV6Kind
  20298. * * BABYLON.VertexBuffer.ColorKind
  20299. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20300. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20301. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20302. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20303. * @param data defines the data source
  20304. * @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
  20305. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20306. * @returns the current mesh
  20307. */
  20308. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20309. return this;
  20310. };
  20311. /**
  20312. * Sets the mesh indices,
  20313. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20314. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20315. * @param totalVertices Defines the total number of vertices
  20316. * @returns the current mesh
  20317. */
  20318. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20319. return this;
  20320. };
  20321. /**
  20322. * Gets a boolean indicating if specific vertex data is present
  20323. * @param kind defines the vertex data kind to use
  20324. * @returns true is data kind is present
  20325. */
  20326. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20327. return false;
  20328. };
  20329. /**
  20330. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20331. * @returns a BoundingInfo
  20332. */
  20333. AbstractMesh.prototype.getBoundingInfo = function () {
  20334. if (this._masterMesh) {
  20335. return this._masterMesh.getBoundingInfo();
  20336. }
  20337. if (!this._boundingInfo) {
  20338. // this._boundingInfo is being created here
  20339. this._updateBoundingInfo();
  20340. }
  20341. // cannot be null.
  20342. return this._boundingInfo;
  20343. };
  20344. /**
  20345. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20346. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20347. * @returns the current mesh
  20348. */
  20349. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20350. if (includeDescendants === void 0) { includeDescendants = true; }
  20351. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20352. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20353. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20354. if (maxDimension === 0) {
  20355. return this;
  20356. }
  20357. var scale = 1 / maxDimension;
  20358. this.scaling.scaleInPlace(scale);
  20359. return this;
  20360. };
  20361. /**
  20362. * Overwrite the current bounding info
  20363. * @param boundingInfo defines the new bounding info
  20364. * @returns the current mesh
  20365. */
  20366. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20367. this._boundingInfo = boundingInfo;
  20368. return this;
  20369. };
  20370. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20371. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20372. get: function () {
  20373. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20374. },
  20375. enumerable: true,
  20376. configurable: true
  20377. });
  20378. /** @hidden */
  20379. AbstractMesh.prototype._preActivate = function () {
  20380. };
  20381. /** @hidden */
  20382. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20383. };
  20384. /** @hidden */
  20385. AbstractMesh.prototype._activate = function (renderId) {
  20386. this._renderId = renderId;
  20387. };
  20388. /**
  20389. * Gets the current world matrix
  20390. * @returns a Matrix
  20391. */
  20392. AbstractMesh.prototype.getWorldMatrix = function () {
  20393. if (this._masterMesh) {
  20394. return this._masterMesh.getWorldMatrix();
  20395. }
  20396. return _super.prototype.getWorldMatrix.call(this);
  20397. };
  20398. /** @hidden */
  20399. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20400. if (this._masterMesh) {
  20401. return this._masterMesh._getWorldMatrixDeterminant();
  20402. }
  20403. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20404. };
  20405. // ================================== Point of View Movement =================================
  20406. /**
  20407. * Perform relative position change from the point of view of behind the front of the mesh.
  20408. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20409. * Supports definition of mesh facing forward or backward
  20410. * @param amountRight defines the distance on the right axis
  20411. * @param amountUp defines the distance on the up axis
  20412. * @param amountForward defines the distance on the forward axis
  20413. * @returns the current mesh
  20414. */
  20415. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20416. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20417. return this;
  20418. };
  20419. /**
  20420. * Calculate relative position change from the point of view of behind the front of the mesh.
  20421. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20422. * Supports definition of mesh facing forward or backward
  20423. * @param amountRight defines the distance on the right axis
  20424. * @param amountUp defines the distance on the up axis
  20425. * @param amountForward defines the distance on the forward axis
  20426. * @returns the new displacement vector
  20427. */
  20428. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20429. var rotMatrix = new BABYLON.Matrix();
  20430. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20431. rotQuaternion.toRotationMatrix(rotMatrix);
  20432. var translationDelta = BABYLON.Vector3.Zero();
  20433. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20434. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20435. return translationDelta;
  20436. };
  20437. // ================================== Point of View Rotation =================================
  20438. /**
  20439. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20440. * Supports definition of mesh facing forward or backward
  20441. * @param flipBack defines the flip
  20442. * @param twirlClockwise defines the twirl
  20443. * @param tiltRight defines the tilt
  20444. * @returns the current mesh
  20445. */
  20446. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20447. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20448. return this;
  20449. };
  20450. /**
  20451. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20452. * Supports definition of mesh facing forward or backward.
  20453. * @param flipBack defines the flip
  20454. * @param twirlClockwise defines the twirl
  20455. * @param tiltRight defines the tilt
  20456. * @returns the new rotation vector
  20457. */
  20458. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20459. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20460. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20461. };
  20462. /**
  20463. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20464. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20465. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20466. * @returns the new bounding vectors
  20467. */
  20468. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20469. if (includeDescendants === void 0) { includeDescendants = true; }
  20470. if (predicate === void 0) { predicate = null; }
  20471. // Ensures that all world matrix will be recomputed.
  20472. this.getScene().incrementRenderId();
  20473. this.computeWorldMatrix(true);
  20474. var min;
  20475. var max;
  20476. var boundingInfo = this.getBoundingInfo();
  20477. if (!this.subMeshes) {
  20478. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20479. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20480. }
  20481. else {
  20482. min = boundingInfo.boundingBox.minimumWorld;
  20483. max = boundingInfo.boundingBox.maximumWorld;
  20484. }
  20485. if (includeDescendants) {
  20486. var descendants = this.getDescendants(false);
  20487. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20488. var descendant = descendants_1[_i];
  20489. var childMesh = descendant;
  20490. childMesh.computeWorldMatrix(true);
  20491. // Filters meshes based on custom predicate function.
  20492. if (predicate && !predicate(childMesh)) {
  20493. continue;
  20494. }
  20495. //make sure we have the needed params to get mix and max
  20496. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20497. continue;
  20498. }
  20499. var childBoundingInfo = childMesh.getBoundingInfo();
  20500. var boundingBox = childBoundingInfo.boundingBox;
  20501. var minBox = boundingBox.minimumWorld;
  20502. var maxBox = boundingBox.maximumWorld;
  20503. BABYLON.Tools.CheckExtends(minBox, min, max);
  20504. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20505. }
  20506. }
  20507. return {
  20508. min: min,
  20509. max: max
  20510. };
  20511. };
  20512. /** @hidden */
  20513. AbstractMesh.prototype._updateBoundingInfo = function () {
  20514. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20515. this._boundingInfo.update(this.worldMatrixFromCache);
  20516. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20517. return this;
  20518. };
  20519. /** @hidden */
  20520. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20521. if (!this.subMeshes) {
  20522. return this;
  20523. }
  20524. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20525. var subMesh = this.subMeshes[subIndex];
  20526. if (!subMesh.IsGlobal) {
  20527. subMesh.updateBoundingInfo(matrix);
  20528. }
  20529. }
  20530. return this;
  20531. };
  20532. /** @hidden */
  20533. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20534. // Bounding info
  20535. this._updateBoundingInfo();
  20536. };
  20537. /**
  20538. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20539. * A mesh is in the frustum if its bounding box intersects the frustum
  20540. * @param frustumPlanes defines the frustum to test
  20541. * @returns true if the mesh is in the frustum planes
  20542. */
  20543. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20544. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20545. };
  20546. /**
  20547. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20548. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20549. * @param frustumPlanes defines the frustum to test
  20550. * @returns true if the mesh is completely in the frustum planes
  20551. */
  20552. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20553. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20554. };
  20555. /**
  20556. * True if the mesh intersects another mesh or a SolidParticle object
  20557. * @param mesh defines a target mesh or SolidParticle to test
  20558. * @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)
  20559. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20560. * @returns true if there is an intersection
  20561. */
  20562. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20563. if (precise === void 0) { precise = false; }
  20564. if (!this._boundingInfo || !mesh._boundingInfo) {
  20565. return false;
  20566. }
  20567. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20568. return true;
  20569. }
  20570. if (includeDescendants) {
  20571. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20572. var child = _a[_i];
  20573. if (child.intersectsMesh(mesh, precise, true)) {
  20574. return true;
  20575. }
  20576. }
  20577. }
  20578. return false;
  20579. };
  20580. /**
  20581. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20582. * @param point defines the point to test
  20583. * @returns true if there is an intersection
  20584. */
  20585. AbstractMesh.prototype.intersectsPoint = function (point) {
  20586. if (!this._boundingInfo) {
  20587. return false;
  20588. }
  20589. return this._boundingInfo.intersectsPoint(point);
  20590. };
  20591. /**
  20592. * Gets the current physics impostor
  20593. * @see http://doc.babylonjs.com/features/physics_engine
  20594. * @returns a physics impostor or null
  20595. */
  20596. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20597. return this.physicsImpostor;
  20598. };
  20599. /**
  20600. * Gets the position of the current mesh in camera space
  20601. * @param camera defines the camera to use
  20602. * @returns a position
  20603. */
  20604. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20605. if (camera === void 0) { camera = null; }
  20606. if (!camera) {
  20607. camera = this.getScene().activeCamera;
  20608. }
  20609. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20610. };
  20611. /**
  20612. * Returns the distance from the mesh to the active camera
  20613. * @param camera defines the camera to use
  20614. * @returns the distance
  20615. */
  20616. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20617. if (camera === void 0) { camera = null; }
  20618. if (!camera) {
  20619. camera = this.getScene().activeCamera;
  20620. }
  20621. return this.absolutePosition.subtract(camera.position).length();
  20622. };
  20623. /**
  20624. * Apply a physic impulse to the mesh
  20625. * @param force defines the force to apply
  20626. * @param contactPoint defines where to apply the force
  20627. * @returns the current mesh
  20628. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20629. */
  20630. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20631. if (!this.physicsImpostor) {
  20632. return this;
  20633. }
  20634. this.physicsImpostor.applyImpulse(force, contactPoint);
  20635. return this;
  20636. };
  20637. /**
  20638. * Creates a physic joint between two meshes
  20639. * @param otherMesh defines the other mesh to use
  20640. * @param pivot1 defines the pivot to use on this mesh
  20641. * @param pivot2 defines the pivot to use on the other mesh
  20642. * @param options defines additional options (can be plugin dependent)
  20643. * @returns the current mesh
  20644. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20645. */
  20646. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20647. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20648. return this;
  20649. }
  20650. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20651. mainPivot: pivot1,
  20652. connectedPivot: pivot2,
  20653. nativeParams: options
  20654. });
  20655. return this;
  20656. };
  20657. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20658. // Collisions
  20659. /**
  20660. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20661. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20662. */
  20663. get: function () {
  20664. return this._checkCollisions;
  20665. },
  20666. set: function (collisionEnabled) {
  20667. this._checkCollisions = collisionEnabled;
  20668. if (this.getScene().workerCollisions) {
  20669. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20670. }
  20671. },
  20672. enumerable: true,
  20673. configurable: true
  20674. });
  20675. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20676. /**
  20677. * Gets Collider object used to compute collisions (not physics)
  20678. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20679. */
  20680. get: function () {
  20681. return this._collider;
  20682. },
  20683. enumerable: true,
  20684. configurable: true
  20685. });
  20686. /**
  20687. * Move the mesh using collision engine
  20688. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20689. * @param displacement defines the requested displacement vector
  20690. * @returns the current mesh
  20691. */
  20692. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20693. var globalPosition = this.getAbsolutePosition();
  20694. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20695. if (!this._collider) {
  20696. this._collider = new BABYLON.Collider();
  20697. }
  20698. this._collider._radius = this.ellipsoid;
  20699. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20700. return this;
  20701. };
  20702. // Submeshes octree
  20703. /**
  20704. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20705. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20706. * @param maxCapacity defines the maximum size of each block (64 by default)
  20707. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20708. * @returns the new octree
  20709. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20710. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20711. */
  20712. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20713. if (maxCapacity === void 0) { maxCapacity = 64; }
  20714. if (maxDepth === void 0) { maxDepth = 2; }
  20715. if (!this._submeshesOctree) {
  20716. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20717. }
  20718. this.computeWorldMatrix(true);
  20719. var boundingInfo = this.getBoundingInfo();
  20720. // Update octree
  20721. var bbox = boundingInfo.boundingBox;
  20722. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20723. return this._submeshesOctree;
  20724. };
  20725. // Collisions
  20726. /** @hidden */
  20727. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20728. this._generatePointsArray();
  20729. if (!this._positions) {
  20730. return this;
  20731. }
  20732. // Transformation
  20733. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20734. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20735. subMesh._lastColliderWorldVertices = [];
  20736. subMesh._trianglePlanes = [];
  20737. var start = subMesh.verticesStart;
  20738. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20739. for (var i = start; i < end; i++) {
  20740. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20741. }
  20742. }
  20743. // Collide
  20744. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20745. if (collider.collisionFound) {
  20746. collider.collidedMesh = this;
  20747. }
  20748. return this;
  20749. };
  20750. /** @hidden */
  20751. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20752. var subMeshes;
  20753. var len;
  20754. // Octrees
  20755. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20756. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20757. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20758. len = intersections.length;
  20759. subMeshes = intersections.data;
  20760. }
  20761. else {
  20762. subMeshes = this.subMeshes;
  20763. len = subMeshes.length;
  20764. }
  20765. for (var index = 0; index < len; index++) {
  20766. var subMesh = subMeshes[index];
  20767. // Bounding test
  20768. if (len > 1 && !subMesh._checkCollision(collider))
  20769. continue;
  20770. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20771. }
  20772. return this;
  20773. };
  20774. /** @hidden */
  20775. AbstractMesh.prototype._checkCollision = function (collider) {
  20776. // Bounding box test
  20777. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20778. return this;
  20779. // Transformation matrix
  20780. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20781. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20782. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20783. return this;
  20784. };
  20785. // Picking
  20786. /** @hidden */
  20787. AbstractMesh.prototype._generatePointsArray = function () {
  20788. return false;
  20789. };
  20790. /**
  20791. * Checks if the passed Ray intersects with the mesh
  20792. * @param ray defines the ray to use
  20793. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20794. * @returns the picking info
  20795. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20796. */
  20797. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20798. var pickingInfo = new BABYLON.PickingInfo();
  20799. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20800. return pickingInfo;
  20801. }
  20802. if (!this._generatePointsArray()) {
  20803. return pickingInfo;
  20804. }
  20805. var intersectInfo = null;
  20806. // Octrees
  20807. var subMeshes;
  20808. var len;
  20809. if (this._submeshesOctree && this.useOctreeForPicking) {
  20810. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20811. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20812. len = intersections.length;
  20813. subMeshes = intersections.data;
  20814. }
  20815. else {
  20816. subMeshes = this.subMeshes;
  20817. len = subMeshes.length;
  20818. }
  20819. for (var index = 0; index < len; index++) {
  20820. var subMesh = subMeshes[index];
  20821. // Bounding test
  20822. if (len > 1 && !subMesh.canIntersects(ray))
  20823. continue;
  20824. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20825. if (currentIntersectInfo) {
  20826. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20827. intersectInfo = currentIntersectInfo;
  20828. intersectInfo.subMeshId = index;
  20829. if (fastCheck) {
  20830. break;
  20831. }
  20832. }
  20833. }
  20834. }
  20835. if (intersectInfo) {
  20836. // Get picked point
  20837. var world = this.getWorldMatrix();
  20838. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20839. var direction = ray.direction.clone();
  20840. direction = direction.scale(intersectInfo.distance);
  20841. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20842. var pickedPoint = worldOrigin.add(worldDirection);
  20843. // Return result
  20844. pickingInfo.hit = true;
  20845. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20846. pickingInfo.pickedPoint = pickedPoint;
  20847. pickingInfo.pickedMesh = this;
  20848. pickingInfo.bu = intersectInfo.bu || 0;
  20849. pickingInfo.bv = intersectInfo.bv || 0;
  20850. pickingInfo.faceId = intersectInfo.faceId;
  20851. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20852. return pickingInfo;
  20853. }
  20854. return pickingInfo;
  20855. };
  20856. /**
  20857. * Clones the current mesh
  20858. * @param name defines the mesh name
  20859. * @param newParent defines the new mesh parent
  20860. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20861. * @returns the new mesh
  20862. */
  20863. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20864. return null;
  20865. };
  20866. /**
  20867. * Disposes all the submeshes of the current meshnp
  20868. * @returns the current mesh
  20869. */
  20870. AbstractMesh.prototype.releaseSubMeshes = function () {
  20871. if (this.subMeshes) {
  20872. while (this.subMeshes.length) {
  20873. this.subMeshes[0].dispose();
  20874. }
  20875. }
  20876. else {
  20877. this.subMeshes = new Array();
  20878. }
  20879. return this;
  20880. };
  20881. /**
  20882. * Releases resources associated with this abstract mesh.
  20883. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20884. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20885. */
  20886. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20887. var _this = this;
  20888. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20889. var index;
  20890. // Smart Array Retainers.
  20891. this.getScene().freeActiveMeshes();
  20892. this.getScene().freeRenderingGroups();
  20893. // Action manager
  20894. if (this.actionManager !== undefined && this.actionManager !== null) {
  20895. this.actionManager.dispose();
  20896. this.actionManager = null;
  20897. }
  20898. // Skeleton
  20899. this._skeleton = null;
  20900. // Physics
  20901. if (this.physicsImpostor) {
  20902. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20903. }
  20904. // Intersections in progress
  20905. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20906. var other = this._intersectionsInProgress[index];
  20907. var pos = other._intersectionsInProgress.indexOf(this);
  20908. other._intersectionsInProgress.splice(pos, 1);
  20909. }
  20910. this._intersectionsInProgress = [];
  20911. // Lights
  20912. var lights = this.getScene().lights;
  20913. lights.forEach(function (light) {
  20914. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20915. if (meshIndex !== -1) {
  20916. light.includedOnlyMeshes.splice(meshIndex, 1);
  20917. }
  20918. meshIndex = light.excludedMeshes.indexOf(_this);
  20919. if (meshIndex !== -1) {
  20920. light.excludedMeshes.splice(meshIndex, 1);
  20921. }
  20922. // Shadow generators
  20923. var generator = light.getShadowGenerator();
  20924. if (generator) {
  20925. var shadowMap = generator.getShadowMap();
  20926. if (shadowMap && shadowMap.renderList) {
  20927. meshIndex = shadowMap.renderList.indexOf(_this);
  20928. if (meshIndex !== -1) {
  20929. shadowMap.renderList.splice(meshIndex, 1);
  20930. }
  20931. }
  20932. }
  20933. });
  20934. // Edges
  20935. if (this._edgesRenderer) {
  20936. this._edgesRenderer.dispose();
  20937. this._edgesRenderer = null;
  20938. }
  20939. // SubMeshes
  20940. if (this.getClassName() !== "InstancedMesh") {
  20941. this.releaseSubMeshes();
  20942. }
  20943. // Octree
  20944. var sceneOctree = this.getScene().selectionOctree;
  20945. if (sceneOctree !== undefined && sceneOctree !== null) {
  20946. var index = sceneOctree.dynamicContent.indexOf(this);
  20947. if (index !== -1) {
  20948. sceneOctree.dynamicContent.splice(index, 1);
  20949. }
  20950. }
  20951. // Query
  20952. var engine = this.getScene().getEngine();
  20953. if (this._occlusionQuery) {
  20954. this._isOcclusionQueryInProgress = false;
  20955. engine.deleteQuery(this._occlusionQuery);
  20956. this._occlusionQuery = null;
  20957. }
  20958. // Engine
  20959. engine.wipeCaches();
  20960. // Remove from scene
  20961. this.getScene().removeMesh(this);
  20962. if (disposeMaterialAndTextures) {
  20963. if (this.material) {
  20964. this.material.dispose(false, true);
  20965. }
  20966. }
  20967. if (!doNotRecurse) {
  20968. // Particles
  20969. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20970. if (this.getScene().particleSystems[index].emitter === this) {
  20971. this.getScene().particleSystems[index].dispose();
  20972. index--;
  20973. }
  20974. }
  20975. }
  20976. // facet data
  20977. if (this._facetDataEnabled) {
  20978. this.disableFacetData();
  20979. }
  20980. this.onAfterWorldMatrixUpdateObservable.clear();
  20981. this.onCollideObservable.clear();
  20982. this.onCollisionPositionChangeObservable.clear();
  20983. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20984. };
  20985. /**
  20986. * Adds the passed mesh as a child to the current mesh
  20987. * @param mesh defines the child mesh
  20988. * @returns the current mesh
  20989. */
  20990. AbstractMesh.prototype.addChild = function (mesh) {
  20991. mesh.setParent(this);
  20992. return this;
  20993. };
  20994. /**
  20995. * Removes the passed mesh from the current mesh children list
  20996. * @param mesh defines the child mesh
  20997. * @returns the current mesh
  20998. */
  20999. AbstractMesh.prototype.removeChild = function (mesh) {
  21000. mesh.setParent(null);
  21001. return this;
  21002. };
  21003. // Facet data
  21004. /** @hidden */
  21005. AbstractMesh.prototype._initFacetData = function () {
  21006. if (!this._facetNormals) {
  21007. this._facetNormals = new Array();
  21008. }
  21009. if (!this._facetPositions) {
  21010. this._facetPositions = new Array();
  21011. }
  21012. if (!this._facetPartitioning) {
  21013. this._facetPartitioning = new Array();
  21014. }
  21015. this._facetNb = (this.getIndices().length / 3) | 0;
  21016. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21017. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21018. for (var f = 0; f < this._facetNb; f++) {
  21019. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21020. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21021. }
  21022. this._facetDataEnabled = true;
  21023. return this;
  21024. };
  21025. /**
  21026. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21027. * This method can be called within the render loop.
  21028. * 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
  21029. * @returns the current mesh
  21030. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21031. */
  21032. AbstractMesh.prototype.updateFacetData = function () {
  21033. if (!this._facetDataEnabled) {
  21034. this._initFacetData();
  21035. }
  21036. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21037. var indices = this.getIndices();
  21038. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21039. var bInfo = this.getBoundingInfo();
  21040. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21041. // init arrays, matrix and sort function on first call
  21042. this._facetDepthSortEnabled = true;
  21043. if (indices instanceof Uint16Array) {
  21044. this._depthSortedIndices = new Uint16Array(indices);
  21045. }
  21046. else if (indices instanceof Uint32Array) {
  21047. this._depthSortedIndices = new Uint32Array(indices);
  21048. }
  21049. else {
  21050. var needs32bits = false;
  21051. for (var i = 0; i < indices.length; i++) {
  21052. if (indices[i] > 65535) {
  21053. needs32bits = true;
  21054. break;
  21055. }
  21056. }
  21057. if (needs32bits) {
  21058. this._depthSortedIndices = new Uint32Array(indices);
  21059. }
  21060. else {
  21061. this._depthSortedIndices = new Uint16Array(indices);
  21062. }
  21063. }
  21064. this._facetDepthSortFunction = function (f1, f2) {
  21065. return (f2.sqDistance - f1.sqDistance);
  21066. };
  21067. if (!this._facetDepthSortFrom) {
  21068. var camera = this.getScene().activeCamera;
  21069. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21070. }
  21071. this._depthSortedFacets = [];
  21072. for (var f = 0; f < this._facetNb; f++) {
  21073. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21074. this._depthSortedFacets.push(depthSortedFacet);
  21075. }
  21076. this._invertedMatrix = BABYLON.Matrix.Identity();
  21077. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21078. }
  21079. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21080. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21081. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21082. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21083. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21084. this._subDiv.max = this._partitioningSubdivisions;
  21085. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21086. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21087. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21088. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21089. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21090. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21091. // set the parameters for ComputeNormals()
  21092. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21093. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21094. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21095. this._facetParameters.bInfo = bInfo;
  21096. this._facetParameters.bbSize = this._bbSize;
  21097. this._facetParameters.subDiv = this._subDiv;
  21098. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21099. this._facetParameters.depthSort = this._facetDepthSort;
  21100. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21101. this.computeWorldMatrix(true);
  21102. this._worldMatrix.invertToRef(this._invertedMatrix);
  21103. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21104. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21105. }
  21106. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21107. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21108. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21109. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21110. var l = (this._depthSortedIndices.length / 3) | 0;
  21111. for (var f = 0; f < l; f++) {
  21112. var sind = this._depthSortedFacets[f].ind;
  21113. this._depthSortedIndices[f * 3] = indices[sind];
  21114. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21115. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21116. }
  21117. this.updateIndices(this._depthSortedIndices);
  21118. }
  21119. return this;
  21120. };
  21121. /**
  21122. * Returns the facetLocalNormals array.
  21123. * The normals are expressed in the mesh local spac
  21124. * @returns an array of Vector3
  21125. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21126. */
  21127. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21128. if (!this._facetNormals) {
  21129. this.updateFacetData();
  21130. }
  21131. return this._facetNormals;
  21132. };
  21133. /**
  21134. * Returns the facetLocalPositions array.
  21135. * The facet positions are expressed in the mesh local space
  21136. * @returns an array of Vector3
  21137. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21138. */
  21139. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21140. if (!this._facetPositions) {
  21141. this.updateFacetData();
  21142. }
  21143. return this._facetPositions;
  21144. };
  21145. /**
  21146. * Returns the facetLocalPartioning array
  21147. * @returns an array of array of numbers
  21148. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21149. */
  21150. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21151. if (!this._facetPartitioning) {
  21152. this.updateFacetData();
  21153. }
  21154. return this._facetPartitioning;
  21155. };
  21156. /**
  21157. * Returns the i-th facet position in the world system.
  21158. * This method allocates a new Vector3 per call
  21159. * @param i defines the facet index
  21160. * @returns a new Vector3
  21161. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21162. */
  21163. AbstractMesh.prototype.getFacetPosition = function (i) {
  21164. var pos = BABYLON.Vector3.Zero();
  21165. this.getFacetPositionToRef(i, pos);
  21166. return pos;
  21167. };
  21168. /**
  21169. * Sets the reference Vector3 with the i-th facet position in the world system
  21170. * @param i defines the facet index
  21171. * @param ref defines the target vector
  21172. * @returns the current mesh
  21173. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21174. */
  21175. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21176. var localPos = (this.getFacetLocalPositions())[i];
  21177. var world = this.getWorldMatrix();
  21178. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21179. return this;
  21180. };
  21181. /**
  21182. * Returns the i-th facet normal in the world system.
  21183. * This method allocates a new Vector3 per call
  21184. * @param i defines the facet index
  21185. * @returns a new Vector3
  21186. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21187. */
  21188. AbstractMesh.prototype.getFacetNormal = function (i) {
  21189. var norm = BABYLON.Vector3.Zero();
  21190. this.getFacetNormalToRef(i, norm);
  21191. return norm;
  21192. };
  21193. /**
  21194. * Sets the reference Vector3 with the i-th facet normal in the world system
  21195. * @param i defines the facet index
  21196. * @param ref defines the target vector
  21197. * @returns the current mesh
  21198. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21199. */
  21200. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21201. var localNorm = (this.getFacetLocalNormals())[i];
  21202. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21203. return this;
  21204. };
  21205. /**
  21206. * 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)
  21207. * @param x defines x coordinate
  21208. * @param y defines y coordinate
  21209. * @param z defines z coordinate
  21210. * @returns the array of facet indexes
  21211. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21212. */
  21213. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21214. var bInfo = this.getBoundingInfo();
  21215. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21216. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21217. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21218. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21219. return null;
  21220. }
  21221. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21222. };
  21223. /**
  21224. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21225. * @param projected sets as the (x,y,z) world projection on the facet
  21226. * @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
  21227. * @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
  21228. * @param x defines x coordinate
  21229. * @param y defines y coordinate
  21230. * @param z defines z coordinate
  21231. * @returns the face index if found (or null instead)
  21232. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21233. */
  21234. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21235. if (checkFace === void 0) { checkFace = false; }
  21236. if (facing === void 0) { facing = true; }
  21237. var world = this.getWorldMatrix();
  21238. var invMat = BABYLON.Tmp.Matrix[5];
  21239. world.invertToRef(invMat);
  21240. var invVect = BABYLON.Tmp.Vector3[8];
  21241. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21242. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21243. if (projected) {
  21244. // tranform the local computed projected vector to world coordinates
  21245. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21246. }
  21247. return closest;
  21248. };
  21249. /**
  21250. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21251. * @param projected sets as the (x,y,z) local projection on the facet
  21252. * @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
  21253. * @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
  21254. * @param x defines x coordinate
  21255. * @param y defines y coordinate
  21256. * @param z defines z coordinate
  21257. * @returns the face index if found (or null instead)
  21258. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21259. */
  21260. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21261. if (checkFace === void 0) { checkFace = false; }
  21262. if (facing === void 0) { facing = true; }
  21263. var closest = null;
  21264. var tmpx = 0.0;
  21265. var tmpy = 0.0;
  21266. var tmpz = 0.0;
  21267. var d = 0.0; // tmp dot facet normal * facet position
  21268. var t0 = 0.0;
  21269. var projx = 0.0;
  21270. var projy = 0.0;
  21271. var projz = 0.0;
  21272. // Get all the facets in the same partitioning block than (x, y, z)
  21273. var facetPositions = this.getFacetLocalPositions();
  21274. var facetNormals = this.getFacetLocalNormals();
  21275. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21276. if (!facetsInBlock) {
  21277. return null;
  21278. }
  21279. // Get the closest facet to (x, y, z)
  21280. var shortest = Number.MAX_VALUE; // init distance vars
  21281. var tmpDistance = shortest;
  21282. var fib; // current facet in the block
  21283. var norm; // current facet normal
  21284. var p0; // current facet barycenter position
  21285. // loop on all the facets in the current partitioning block
  21286. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21287. fib = facetsInBlock[idx];
  21288. norm = facetNormals[fib];
  21289. p0 = facetPositions[fib];
  21290. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21291. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21292. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21293. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21294. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21295. projx = x + norm.x * t0;
  21296. projy = y + norm.y * t0;
  21297. projz = z + norm.z * t0;
  21298. tmpx = projx - x;
  21299. tmpy = projy - y;
  21300. tmpz = projz - z;
  21301. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21302. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21303. shortest = tmpDistance;
  21304. closest = fib;
  21305. if (projected) {
  21306. projected.x = projx;
  21307. projected.y = projy;
  21308. projected.z = projz;
  21309. }
  21310. }
  21311. }
  21312. }
  21313. return closest;
  21314. };
  21315. /**
  21316. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21317. * @returns the parameters
  21318. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21319. */
  21320. AbstractMesh.prototype.getFacetDataParameters = function () {
  21321. return this._facetParameters;
  21322. };
  21323. /**
  21324. * Disables the feature FacetData and frees the related memory
  21325. * @returns the current mesh
  21326. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21327. */
  21328. AbstractMesh.prototype.disableFacetData = function () {
  21329. if (this._facetDataEnabled) {
  21330. this._facetDataEnabled = false;
  21331. this._facetPositions = new Array();
  21332. this._facetNormals = new Array();
  21333. this._facetPartitioning = new Array();
  21334. this._facetParameters = null;
  21335. this._depthSortedIndices = new Uint32Array(0);
  21336. }
  21337. return this;
  21338. };
  21339. /**
  21340. * Updates the AbstractMesh indices array
  21341. * @param indices defines the data source
  21342. * @returns the current mesh
  21343. */
  21344. AbstractMesh.prototype.updateIndices = function (indices) {
  21345. return this;
  21346. };
  21347. /**
  21348. * Creates new normals data for the mesh
  21349. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21350. * @returns the current mesh
  21351. */
  21352. AbstractMesh.prototype.createNormals = function (updatable) {
  21353. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21354. var indices = this.getIndices();
  21355. var normals;
  21356. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21357. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21358. }
  21359. else {
  21360. normals = [];
  21361. }
  21362. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21363. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21364. return this;
  21365. };
  21366. /**
  21367. * Align the mesh with a normal
  21368. * @param normal defines the normal to use
  21369. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21370. * @returns the current mesh
  21371. */
  21372. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21373. if (!upDirection) {
  21374. upDirection = BABYLON.Axis.Y;
  21375. }
  21376. var axisX = BABYLON.Tmp.Vector3[0];
  21377. var axisZ = BABYLON.Tmp.Vector3[1];
  21378. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21379. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21380. if (this.rotationQuaternion) {
  21381. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21382. }
  21383. else {
  21384. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21385. }
  21386. return this;
  21387. };
  21388. /** @hidden */
  21389. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21390. var engine = this.getEngine();
  21391. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21392. this._isOccluded = false;
  21393. return;
  21394. }
  21395. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21396. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21397. if (isOcclusionQueryAvailable) {
  21398. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21399. this._isOcclusionQueryInProgress = false;
  21400. this._occlusionInternalRetryCounter = 0;
  21401. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21402. }
  21403. else {
  21404. this._occlusionInternalRetryCounter++;
  21405. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21406. this._isOcclusionQueryInProgress = false;
  21407. this._occlusionInternalRetryCounter = 0;
  21408. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21409. // if strict continue the last state of the object.
  21410. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21411. }
  21412. else {
  21413. return;
  21414. }
  21415. }
  21416. }
  21417. var scene = this.getScene();
  21418. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21419. if (!this._occlusionQuery) {
  21420. this._occlusionQuery = engine.createQuery();
  21421. }
  21422. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21423. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21424. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21425. this._isOcclusionQueryInProgress = true;
  21426. };
  21427. /** No occlusion */
  21428. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21429. /** Occlusion set to optimisitic */
  21430. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21431. /** Occlusion set to strict */
  21432. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21433. /** Use an accurante occlusion algorithm */
  21434. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21435. /** Use a conservative occlusion algorithm */
  21436. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21437. return AbstractMesh;
  21438. }(BABYLON.TransformNode));
  21439. BABYLON.AbstractMesh = AbstractMesh;
  21440. })(BABYLON || (BABYLON = {}));
  21441. //# sourceMappingURL=babylon.abstractMesh.js.map
  21442. var BABYLON;
  21443. (function (BABYLON) {
  21444. /**
  21445. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21446. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21447. * 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.
  21448. */
  21449. var Light = /** @class */ (function (_super) {
  21450. __extends(Light, _super);
  21451. /**
  21452. * Creates a Light object in the scene.
  21453. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21454. * @param name The firendly name of the light
  21455. * @param scene The scene the light belongs too
  21456. */
  21457. function Light(name, scene) {
  21458. var _this = _super.call(this, name, scene) || this;
  21459. /**
  21460. * Diffuse gives the basic color to an object.
  21461. */
  21462. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21463. /**
  21464. * Specular produces a highlight color on an object.
  21465. * Note: This is note affecting PBR materials.
  21466. */
  21467. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21468. /**
  21469. * Strength of the light.
  21470. * Note: By default it is define in the framework own unit.
  21471. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21472. */
  21473. _this.intensity = 1.0;
  21474. /**
  21475. * Defines how far from the source the light is impacting in scene units.
  21476. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21477. */
  21478. _this.range = Number.MAX_VALUE;
  21479. /**
  21480. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21481. * of light.
  21482. */
  21483. _this._photometricScale = 1.0;
  21484. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21485. _this._radius = 0.00001;
  21486. /**
  21487. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21488. * exceeding the number allowed of the materials.
  21489. */
  21490. _this.renderPriority = 0;
  21491. _this._shadowEnabled = true;
  21492. _this._excludeWithLayerMask = 0;
  21493. _this._includeOnlyWithLayerMask = 0;
  21494. _this._lightmapMode = 0;
  21495. /**
  21496. * @hidden Internal use only.
  21497. */
  21498. _this._excludedMeshesIds = new Array();
  21499. /**
  21500. * @hidden Internal use only.
  21501. */
  21502. _this._includedOnlyMeshesIds = new Array();
  21503. _this.getScene().addLight(_this);
  21504. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21505. _this._buildUniformLayout();
  21506. _this.includedOnlyMeshes = new Array();
  21507. _this.excludedMeshes = new Array();
  21508. _this._resyncMeshes();
  21509. return _this;
  21510. }
  21511. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21512. /**
  21513. * If every light affecting the material is in this lightmapMode,
  21514. * material.lightmapTexture adds or multiplies
  21515. * (depends on material.useLightmapAsShadowmap)
  21516. * after every other light calculations.
  21517. */
  21518. get: function () {
  21519. return Light._LIGHTMAP_DEFAULT;
  21520. },
  21521. enumerable: true,
  21522. configurable: true
  21523. });
  21524. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21525. /**
  21526. * material.lightmapTexture as only diffuse lighting from this light
  21527. * adds only specular lighting from this light
  21528. * adds dynamic shadows
  21529. */
  21530. get: function () {
  21531. return Light._LIGHTMAP_SPECULAR;
  21532. },
  21533. enumerable: true,
  21534. configurable: true
  21535. });
  21536. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21537. /**
  21538. * material.lightmapTexture as only lighting
  21539. * no light calculation from this light
  21540. * only adds dynamic shadows from this light
  21541. */
  21542. get: function () {
  21543. return Light._LIGHTMAP_SHADOWSONLY;
  21544. },
  21545. enumerable: true,
  21546. configurable: true
  21547. });
  21548. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21549. /**
  21550. * Each light type uses the default quantity according to its type:
  21551. * point/spot lights use luminous intensity
  21552. * directional lights use illuminance
  21553. */
  21554. get: function () {
  21555. return Light._INTENSITYMODE_AUTOMATIC;
  21556. },
  21557. enumerable: true,
  21558. configurable: true
  21559. });
  21560. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21561. /**
  21562. * lumen (lm)
  21563. */
  21564. get: function () {
  21565. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21566. },
  21567. enumerable: true,
  21568. configurable: true
  21569. });
  21570. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21571. /**
  21572. * candela (lm/sr)
  21573. */
  21574. get: function () {
  21575. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21576. },
  21577. enumerable: true,
  21578. configurable: true
  21579. });
  21580. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21581. /**
  21582. * lux (lm/m^2)
  21583. */
  21584. get: function () {
  21585. return Light._INTENSITYMODE_ILLUMINANCE;
  21586. },
  21587. enumerable: true,
  21588. configurable: true
  21589. });
  21590. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21591. /**
  21592. * nit (cd/m^2)
  21593. */
  21594. get: function () {
  21595. return Light._INTENSITYMODE_LUMINANCE;
  21596. },
  21597. enumerable: true,
  21598. configurable: true
  21599. });
  21600. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21601. /**
  21602. * Light type const id of the point light.
  21603. */
  21604. get: function () {
  21605. return Light._LIGHTTYPEID_POINTLIGHT;
  21606. },
  21607. enumerable: true,
  21608. configurable: true
  21609. });
  21610. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21611. /**
  21612. * Light type const id of the directional light.
  21613. */
  21614. get: function () {
  21615. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21616. },
  21617. enumerable: true,
  21618. configurable: true
  21619. });
  21620. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21621. /**
  21622. * Light type const id of the spot light.
  21623. */
  21624. get: function () {
  21625. return Light._LIGHTTYPEID_SPOTLIGHT;
  21626. },
  21627. enumerable: true,
  21628. configurable: true
  21629. });
  21630. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21631. /**
  21632. * Light type const id of the hemispheric light.
  21633. */
  21634. get: function () {
  21635. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. Object.defineProperty(Light.prototype, "intensityMode", {
  21641. /**
  21642. * Gets the photometric scale used to interpret the intensity.
  21643. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21644. */
  21645. get: function () {
  21646. return this._intensityMode;
  21647. },
  21648. /**
  21649. * Sets the photometric scale used to interpret the intensity.
  21650. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21651. */
  21652. set: function (value) {
  21653. this._intensityMode = value;
  21654. this._computePhotometricScale();
  21655. },
  21656. enumerable: true,
  21657. configurable: true
  21658. });
  21659. ;
  21660. ;
  21661. Object.defineProperty(Light.prototype, "radius", {
  21662. /**
  21663. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21664. */
  21665. get: function () {
  21666. return this._radius;
  21667. },
  21668. /**
  21669. * sets the light radius used by PBR Materials to simulate soft area lights.
  21670. */
  21671. set: function (value) {
  21672. this._radius = value;
  21673. this._computePhotometricScale();
  21674. },
  21675. enumerable: true,
  21676. configurable: true
  21677. });
  21678. ;
  21679. ;
  21680. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21681. /**
  21682. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21683. * the current shadow generator.
  21684. */
  21685. get: function () {
  21686. return this._shadowEnabled;
  21687. },
  21688. /**
  21689. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21690. * the current shadow generator.
  21691. */
  21692. set: function (value) {
  21693. if (this._shadowEnabled === value) {
  21694. return;
  21695. }
  21696. this._shadowEnabled = value;
  21697. this._markMeshesAsLightDirty();
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21703. /**
  21704. * Gets the only meshes impacted by this light.
  21705. */
  21706. get: function () {
  21707. return this._includedOnlyMeshes;
  21708. },
  21709. /**
  21710. * Sets the only meshes impacted by this light.
  21711. */
  21712. set: function (value) {
  21713. this._includedOnlyMeshes = value;
  21714. this._hookArrayForIncludedOnly(value);
  21715. },
  21716. enumerable: true,
  21717. configurable: true
  21718. });
  21719. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21720. /**
  21721. * Gets the meshes not impacted by this light.
  21722. */
  21723. get: function () {
  21724. return this._excludedMeshes;
  21725. },
  21726. /**
  21727. * Sets the meshes not impacted by this light.
  21728. */
  21729. set: function (value) {
  21730. this._excludedMeshes = value;
  21731. this._hookArrayForExcluded(value);
  21732. },
  21733. enumerable: true,
  21734. configurable: true
  21735. });
  21736. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21737. /**
  21738. * Gets the layer id use to find what meshes are not impacted by the light.
  21739. * Inactive if 0
  21740. */
  21741. get: function () {
  21742. return this._excludeWithLayerMask;
  21743. },
  21744. /**
  21745. * Sets the layer id use to find what meshes are not impacted by the light.
  21746. * Inactive if 0
  21747. */
  21748. set: function (value) {
  21749. this._excludeWithLayerMask = value;
  21750. this._resyncMeshes();
  21751. },
  21752. enumerable: true,
  21753. configurable: true
  21754. });
  21755. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21756. /**
  21757. * Gets the layer id use to find what meshes are impacted by the light.
  21758. * Inactive if 0
  21759. */
  21760. get: function () {
  21761. return this._includeOnlyWithLayerMask;
  21762. },
  21763. /**
  21764. * Sets the layer id use to find what meshes are impacted by the light.
  21765. * Inactive if 0
  21766. */
  21767. set: function (value) {
  21768. this._includeOnlyWithLayerMask = value;
  21769. this._resyncMeshes();
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. Object.defineProperty(Light.prototype, "lightmapMode", {
  21775. /**
  21776. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21777. */
  21778. get: function () {
  21779. return this._lightmapMode;
  21780. },
  21781. /**
  21782. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21783. */
  21784. set: function (value) {
  21785. if (this._lightmapMode === value) {
  21786. return;
  21787. }
  21788. this._lightmapMode = value;
  21789. this._markMeshesAsLightDirty();
  21790. },
  21791. enumerable: true,
  21792. configurable: true
  21793. });
  21794. /**
  21795. * Returns the string "Light".
  21796. * @returns the class name
  21797. */
  21798. Light.prototype.getClassName = function () {
  21799. return "Light";
  21800. };
  21801. /**
  21802. * Converts the light information to a readable string for debug purpose.
  21803. * @param fullDetails Supports for multiple levels of logging within scene loading
  21804. * @returns the human readable light info
  21805. */
  21806. Light.prototype.toString = function (fullDetails) {
  21807. var ret = "Name: " + this.name;
  21808. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21809. if (this.animations) {
  21810. for (var i = 0; i < this.animations.length; i++) {
  21811. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21812. }
  21813. }
  21814. if (fullDetails) {
  21815. }
  21816. return ret;
  21817. };
  21818. /**
  21819. * Set the enabled state of this node.
  21820. * @param value - the new enabled state
  21821. */
  21822. Light.prototype.setEnabled = function (value) {
  21823. _super.prototype.setEnabled.call(this, value);
  21824. this._resyncMeshes();
  21825. };
  21826. /**
  21827. * Returns the Light associated shadow generator if any.
  21828. * @return the associated shadow generator.
  21829. */
  21830. Light.prototype.getShadowGenerator = function () {
  21831. return this._shadowGenerator;
  21832. };
  21833. /**
  21834. * Returns a Vector3, the absolute light position in the World.
  21835. * @returns the world space position of the light
  21836. */
  21837. Light.prototype.getAbsolutePosition = function () {
  21838. return BABYLON.Vector3.Zero();
  21839. };
  21840. /**
  21841. * Specifies if the light will affect the passed mesh.
  21842. * @param mesh The mesh to test against the light
  21843. * @return true the mesh is affected otherwise, false.
  21844. */
  21845. Light.prototype.canAffectMesh = function (mesh) {
  21846. if (!mesh) {
  21847. return true;
  21848. }
  21849. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21850. return false;
  21851. }
  21852. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21853. return false;
  21854. }
  21855. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21856. return false;
  21857. }
  21858. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21859. return false;
  21860. }
  21861. return true;
  21862. };
  21863. /**
  21864. * Computes and Returns the light World matrix.
  21865. * @returns the world matrix
  21866. */
  21867. Light.prototype.getWorldMatrix = function () {
  21868. this._currentRenderId = this.getScene().getRenderId();
  21869. this._childRenderId = this._currentRenderId;
  21870. var worldMatrix = this._getWorldMatrix();
  21871. if (this.parent && this.parent.getWorldMatrix) {
  21872. if (!this._parentedWorldMatrix) {
  21873. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21874. }
  21875. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21876. this._markSyncedWithParent();
  21877. return this._parentedWorldMatrix;
  21878. }
  21879. return worldMatrix;
  21880. };
  21881. /**
  21882. * Sort function to order lights for rendering.
  21883. * @param a First Light object to compare to second.
  21884. * @param b Second Light object to compare first.
  21885. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21886. */
  21887. Light.CompareLightsPriority = function (a, b) {
  21888. //shadow-casting lights have priority over non-shadow-casting lights
  21889. //the renderPrioirty is a secondary sort criterion
  21890. if (a.shadowEnabled !== b.shadowEnabled) {
  21891. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21892. }
  21893. return b.renderPriority - a.renderPriority;
  21894. };
  21895. /**
  21896. * Releases resources associated with this node.
  21897. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21898. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21899. */
  21900. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21901. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21902. if (this._shadowGenerator) {
  21903. this._shadowGenerator.dispose();
  21904. this._shadowGenerator = null;
  21905. }
  21906. // Animations
  21907. this.getScene().stopAnimation(this);
  21908. // Remove from meshes
  21909. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21910. var mesh = _a[_i];
  21911. mesh._removeLightSource(this);
  21912. }
  21913. this._uniformBuffer.dispose();
  21914. // Remove from scene
  21915. this.getScene().removeLight(this);
  21916. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21917. };
  21918. /**
  21919. * Returns the light type ID (integer).
  21920. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21921. */
  21922. Light.prototype.getTypeID = function () {
  21923. return 0;
  21924. };
  21925. /**
  21926. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21927. * @returns the scaled intensity in intensity mode unit
  21928. */
  21929. Light.prototype.getScaledIntensity = function () {
  21930. return this._photometricScale * this.intensity;
  21931. };
  21932. /**
  21933. * Returns a new Light object, named "name", from the current one.
  21934. * @param name The name of the cloned light
  21935. * @returns the new created light
  21936. */
  21937. Light.prototype.clone = function (name) {
  21938. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21939. if (!constructor) {
  21940. return null;
  21941. }
  21942. return BABYLON.SerializationHelper.Clone(constructor, this);
  21943. };
  21944. /**
  21945. * Serializes the current light into a Serialization object.
  21946. * @returns the serialized object.
  21947. */
  21948. Light.prototype.serialize = function () {
  21949. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21950. // Type
  21951. serializationObject.type = this.getTypeID();
  21952. // Parent
  21953. if (this.parent) {
  21954. serializationObject.parentId = this.parent.id;
  21955. }
  21956. // Inclusion / exclusions
  21957. if (this.excludedMeshes.length > 0) {
  21958. serializationObject.excludedMeshesIds = [];
  21959. this.excludedMeshes.forEach(function (mesh) {
  21960. serializationObject.excludedMeshesIds.push(mesh.id);
  21961. });
  21962. }
  21963. if (this.includedOnlyMeshes.length > 0) {
  21964. serializationObject.includedOnlyMeshesIds = [];
  21965. this.includedOnlyMeshes.forEach(function (mesh) {
  21966. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21967. });
  21968. }
  21969. // Animations
  21970. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21971. serializationObject.ranges = this.serializeAnimationRanges();
  21972. return serializationObject;
  21973. };
  21974. /**
  21975. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21976. * This new light is named "name" and added to the passed scene.
  21977. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21978. * @param name The friendly name of the light
  21979. * @param scene The scene the new light will belong to
  21980. * @returns the constructor function
  21981. */
  21982. Light.GetConstructorFromName = function (type, name, scene) {
  21983. switch (type) {
  21984. case 0:
  21985. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21986. case 1:
  21987. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21988. case 2:
  21989. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21990. case 3:
  21991. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21992. }
  21993. return null;
  21994. };
  21995. /**
  21996. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21997. * @param parsedLight The JSON representation of the light
  21998. * @param scene The scene to create the parsed light in
  21999. * @returns the created light after parsing
  22000. */
  22001. Light.Parse = function (parsedLight, scene) {
  22002. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22003. if (!constructor) {
  22004. return null;
  22005. }
  22006. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22007. // Inclusion / exclusions
  22008. if (parsedLight.excludedMeshesIds) {
  22009. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22010. }
  22011. if (parsedLight.includedOnlyMeshesIds) {
  22012. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22013. }
  22014. // Parent
  22015. if (parsedLight.parentId) {
  22016. light._waitingParentId = parsedLight.parentId;
  22017. }
  22018. // Animations
  22019. if (parsedLight.animations) {
  22020. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22021. var parsedAnimation = parsedLight.animations[animationIndex];
  22022. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22023. }
  22024. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22025. }
  22026. if (parsedLight.autoAnimate) {
  22027. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22028. }
  22029. return light;
  22030. };
  22031. Light.prototype._hookArrayForExcluded = function (array) {
  22032. var _this = this;
  22033. var oldPush = array.push;
  22034. array.push = function () {
  22035. var items = [];
  22036. for (var _i = 0; _i < arguments.length; _i++) {
  22037. items[_i] = arguments[_i];
  22038. }
  22039. var result = oldPush.apply(array, items);
  22040. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22041. var item = items_1[_a];
  22042. item._resyncLighSource(_this);
  22043. }
  22044. return result;
  22045. };
  22046. var oldSplice = array.splice;
  22047. array.splice = function (index, deleteCount) {
  22048. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22049. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22050. var item = deleted_1[_i];
  22051. item._resyncLighSource(_this);
  22052. }
  22053. return deleted;
  22054. };
  22055. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22056. var item = array_1[_i];
  22057. item._resyncLighSource(this);
  22058. }
  22059. };
  22060. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22061. var _this = this;
  22062. var oldPush = array.push;
  22063. array.push = function () {
  22064. var items = [];
  22065. for (var _i = 0; _i < arguments.length; _i++) {
  22066. items[_i] = arguments[_i];
  22067. }
  22068. var result = oldPush.apply(array, items);
  22069. _this._resyncMeshes();
  22070. return result;
  22071. };
  22072. var oldSplice = array.splice;
  22073. array.splice = function (index, deleteCount) {
  22074. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22075. _this._resyncMeshes();
  22076. return deleted;
  22077. };
  22078. this._resyncMeshes();
  22079. };
  22080. Light.prototype._resyncMeshes = function () {
  22081. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22082. var mesh = _a[_i];
  22083. mesh._resyncLighSource(this);
  22084. }
  22085. };
  22086. /**
  22087. * Forces the meshes to update their light related information in their rendering used effects
  22088. * @hidden Internal Use Only
  22089. */
  22090. Light.prototype._markMeshesAsLightDirty = function () {
  22091. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22092. var mesh = _a[_i];
  22093. if (mesh._lightSources.indexOf(this) !== -1) {
  22094. mesh._markSubMeshesAsLightDirty();
  22095. }
  22096. }
  22097. };
  22098. /**
  22099. * Recomputes the cached photometric scale if needed.
  22100. */
  22101. Light.prototype._computePhotometricScale = function () {
  22102. this._photometricScale = this._getPhotometricScale();
  22103. this.getScene().resetCachedMaterial();
  22104. };
  22105. /**
  22106. * Returns the Photometric Scale according to the light type and intensity mode.
  22107. */
  22108. Light.prototype._getPhotometricScale = function () {
  22109. var photometricScale = 0.0;
  22110. var lightTypeID = this.getTypeID();
  22111. //get photometric mode
  22112. var photometricMode = this.intensityMode;
  22113. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22114. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22115. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22116. }
  22117. else {
  22118. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22119. }
  22120. }
  22121. //compute photometric scale
  22122. switch (lightTypeID) {
  22123. case Light.LIGHTTYPEID_POINTLIGHT:
  22124. case Light.LIGHTTYPEID_SPOTLIGHT:
  22125. switch (photometricMode) {
  22126. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22127. photometricScale = 1.0 / (4.0 * Math.PI);
  22128. break;
  22129. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22130. photometricScale = 1.0;
  22131. break;
  22132. case Light.INTENSITYMODE_LUMINANCE:
  22133. photometricScale = this.radius * this.radius;
  22134. break;
  22135. }
  22136. break;
  22137. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22138. switch (photometricMode) {
  22139. case Light.INTENSITYMODE_ILLUMINANCE:
  22140. photometricScale = 1.0;
  22141. break;
  22142. case Light.INTENSITYMODE_LUMINANCE:
  22143. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22144. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22145. var apexAngleRadians = this.radius;
  22146. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22147. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22148. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22149. photometricScale = solidAngle;
  22150. break;
  22151. }
  22152. break;
  22153. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22154. // No fall off in hemisperic light.
  22155. photometricScale = 1.0;
  22156. break;
  22157. }
  22158. return photometricScale;
  22159. };
  22160. /**
  22161. * Reorder the light in the scene according to their defined priority.
  22162. * @hidden Internal Use Only
  22163. */
  22164. Light.prototype._reorderLightsInScene = function () {
  22165. var scene = this.getScene();
  22166. if (this._renderPriority != 0) {
  22167. scene.requireLightSorting = true;
  22168. }
  22169. this.getScene().sortLightsByPriority();
  22170. };
  22171. //lightmapMode Consts
  22172. Light._LIGHTMAP_DEFAULT = 0;
  22173. Light._LIGHTMAP_SPECULAR = 1;
  22174. Light._LIGHTMAP_SHADOWSONLY = 2;
  22175. // Intensity Mode Consts
  22176. Light._INTENSITYMODE_AUTOMATIC = 0;
  22177. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22178. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22179. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22180. Light._INTENSITYMODE_LUMINANCE = 4;
  22181. // Light types ids const.
  22182. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22183. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22184. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22185. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22186. __decorate([
  22187. BABYLON.serializeAsColor3()
  22188. ], Light.prototype, "diffuse", void 0);
  22189. __decorate([
  22190. BABYLON.serializeAsColor3()
  22191. ], Light.prototype, "specular", void 0);
  22192. __decorate([
  22193. BABYLON.serialize()
  22194. ], Light.prototype, "intensity", void 0);
  22195. __decorate([
  22196. BABYLON.serialize()
  22197. ], Light.prototype, "range", void 0);
  22198. __decorate([
  22199. BABYLON.serialize()
  22200. ], Light.prototype, "intensityMode", null);
  22201. __decorate([
  22202. BABYLON.serialize()
  22203. ], Light.prototype, "radius", null);
  22204. __decorate([
  22205. BABYLON.serialize()
  22206. ], Light.prototype, "_renderPriority", void 0);
  22207. __decorate([
  22208. BABYLON.expandToProperty("_reorderLightsInScene")
  22209. ], Light.prototype, "renderPriority", void 0);
  22210. __decorate([
  22211. BABYLON.serialize("shadowEnabled")
  22212. ], Light.prototype, "_shadowEnabled", void 0);
  22213. __decorate([
  22214. BABYLON.serialize("excludeWithLayerMask")
  22215. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22216. __decorate([
  22217. BABYLON.serialize("includeOnlyWithLayerMask")
  22218. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22219. __decorate([
  22220. BABYLON.serialize("lightmapMode")
  22221. ], Light.prototype, "_lightmapMode", void 0);
  22222. return Light;
  22223. }(BABYLON.Node));
  22224. BABYLON.Light = Light;
  22225. })(BABYLON || (BABYLON = {}));
  22226. //# sourceMappingURL=babylon.light.js.map
  22227. var BABYLON;
  22228. (function (BABYLON) {
  22229. var Camera = /** @class */ (function (_super) {
  22230. __extends(Camera, _super);
  22231. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22232. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22233. var _this = _super.call(this, name, scene) || this;
  22234. /**
  22235. * The vector the camera should consider as up.
  22236. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22237. */
  22238. _this.upVector = BABYLON.Vector3.Up();
  22239. _this.orthoLeft = null;
  22240. _this.orthoRight = null;
  22241. _this.orthoBottom = null;
  22242. _this.orthoTop = null;
  22243. /**
  22244. * FOV is set in Radians. (default is 0.8)
  22245. */
  22246. _this.fov = 0.8;
  22247. _this.minZ = 1;
  22248. _this.maxZ = 10000.0;
  22249. _this.inertia = 0.9;
  22250. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22251. _this.isIntermediate = false;
  22252. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22253. /**
  22254. * Restricts the camera to viewing objects with the same layerMask.
  22255. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22256. */
  22257. _this.layerMask = 0x0FFFFFFF;
  22258. /**
  22259. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22260. */
  22261. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22262. // Camera rig members
  22263. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22264. _this._rigCameras = new Array();
  22265. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22266. _this._skipRendering = false;
  22267. _this.customRenderTargets = new Array();
  22268. // Observables
  22269. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22270. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22271. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22272. _this.onRestoreStateObservable = new BABYLON.Observable();
  22273. // Cache
  22274. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22275. _this._projectionMatrix = new BABYLON.Matrix();
  22276. _this._doNotComputeProjectionMatrix = false;
  22277. _this._worldMatrix = BABYLON.Matrix.Identity();
  22278. _this._postProcesses = new Array();
  22279. _this._transformMatrix = BABYLON.Matrix.Zero();
  22280. _this._activeMeshes = new BABYLON.SmartArray(256);
  22281. _this._globalPosition = BABYLON.Vector3.Zero();
  22282. _this._refreshFrustumPlanes = true;
  22283. _this.getScene().addCamera(_this);
  22284. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22285. _this.getScene().activeCamera = _this;
  22286. }
  22287. _this.position = position;
  22288. return _this;
  22289. }
  22290. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22291. get: function () {
  22292. return Camera._PERSPECTIVE_CAMERA;
  22293. },
  22294. enumerable: true,
  22295. configurable: true
  22296. });
  22297. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22298. get: function () {
  22299. return Camera._ORTHOGRAPHIC_CAMERA;
  22300. },
  22301. enumerable: true,
  22302. configurable: true
  22303. });
  22304. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22305. /**
  22306. * This is the default FOV mode for perspective cameras.
  22307. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22308. *
  22309. */
  22310. get: function () {
  22311. return Camera._FOVMODE_VERTICAL_FIXED;
  22312. },
  22313. enumerable: true,
  22314. configurable: true
  22315. });
  22316. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22317. /**
  22318. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22319. *
  22320. */
  22321. get: function () {
  22322. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22323. },
  22324. enumerable: true,
  22325. configurable: true
  22326. });
  22327. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22328. get: function () {
  22329. return Camera._RIG_MODE_NONE;
  22330. },
  22331. enumerable: true,
  22332. configurable: true
  22333. });
  22334. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22335. get: function () {
  22336. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22337. },
  22338. enumerable: true,
  22339. configurable: true
  22340. });
  22341. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22342. get: function () {
  22343. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22344. },
  22345. enumerable: true,
  22346. configurable: true
  22347. });
  22348. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22349. get: function () {
  22350. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22351. },
  22352. enumerable: true,
  22353. configurable: true
  22354. });
  22355. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22356. get: function () {
  22357. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22358. },
  22359. enumerable: true,
  22360. configurable: true
  22361. });
  22362. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22363. get: function () {
  22364. return Camera._RIG_MODE_VR;
  22365. },
  22366. enumerable: true,
  22367. configurable: true
  22368. });
  22369. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22370. get: function () {
  22371. return Camera._RIG_MODE_WEBVR;
  22372. },
  22373. enumerable: true,
  22374. configurable: true
  22375. });
  22376. /**
  22377. * Store current camera state (fov, position, etc..)
  22378. */
  22379. Camera.prototype.storeState = function () {
  22380. this._stateStored = true;
  22381. this._storedFov = this.fov;
  22382. return this;
  22383. };
  22384. /**
  22385. * Restores the camera state values if it has been stored. You must call storeState() first
  22386. */
  22387. Camera.prototype._restoreStateValues = function () {
  22388. if (!this._stateStored) {
  22389. return false;
  22390. }
  22391. this.fov = this._storedFov;
  22392. return true;
  22393. };
  22394. /**
  22395. * Restored camera state. You must call storeState() first
  22396. */
  22397. Camera.prototype.restoreState = function () {
  22398. if (this._restoreStateValues()) {
  22399. this.onRestoreStateObservable.notifyObservers(this);
  22400. return true;
  22401. }
  22402. return false;
  22403. };
  22404. Camera.prototype.getClassName = function () {
  22405. return "Camera";
  22406. };
  22407. /**
  22408. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22409. */
  22410. Camera.prototype.toString = function (fullDetails) {
  22411. var ret = "Name: " + this.name;
  22412. ret += ", type: " + this.getClassName();
  22413. if (this.animations) {
  22414. for (var i = 0; i < this.animations.length; i++) {
  22415. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22416. }
  22417. }
  22418. if (fullDetails) {
  22419. }
  22420. return ret;
  22421. };
  22422. Object.defineProperty(Camera.prototype, "globalPosition", {
  22423. get: function () {
  22424. return this._globalPosition;
  22425. },
  22426. enumerable: true,
  22427. configurable: true
  22428. });
  22429. Camera.prototype.getActiveMeshes = function () {
  22430. return this._activeMeshes;
  22431. };
  22432. Camera.prototype.isActiveMesh = function (mesh) {
  22433. return (this._activeMeshes.indexOf(mesh) !== -1);
  22434. };
  22435. /**
  22436. * Is this camera ready to be used/rendered
  22437. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22438. * @return true if the camera is ready
  22439. */
  22440. Camera.prototype.isReady = function (completeCheck) {
  22441. if (completeCheck === void 0) { completeCheck = false; }
  22442. if (completeCheck) {
  22443. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22444. var pp = _a[_i];
  22445. if (pp && !pp.isReady()) {
  22446. return false;
  22447. }
  22448. }
  22449. }
  22450. return _super.prototype.isReady.call(this, completeCheck);
  22451. };
  22452. //Cache
  22453. Camera.prototype._initCache = function () {
  22454. _super.prototype._initCache.call(this);
  22455. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22456. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22457. this._cache.mode = undefined;
  22458. this._cache.minZ = undefined;
  22459. this._cache.maxZ = undefined;
  22460. this._cache.fov = undefined;
  22461. this._cache.fovMode = undefined;
  22462. this._cache.aspectRatio = undefined;
  22463. this._cache.orthoLeft = undefined;
  22464. this._cache.orthoRight = undefined;
  22465. this._cache.orthoBottom = undefined;
  22466. this._cache.orthoTop = undefined;
  22467. this._cache.renderWidth = undefined;
  22468. this._cache.renderHeight = undefined;
  22469. };
  22470. Camera.prototype._updateCache = function (ignoreParentClass) {
  22471. if (!ignoreParentClass) {
  22472. _super.prototype._updateCache.call(this);
  22473. }
  22474. this._cache.position.copyFrom(this.position);
  22475. this._cache.upVector.copyFrom(this.upVector);
  22476. };
  22477. // Synchronized
  22478. Camera.prototype._isSynchronized = function () {
  22479. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22480. };
  22481. Camera.prototype._isSynchronizedViewMatrix = function () {
  22482. if (!_super.prototype._isSynchronized.call(this))
  22483. return false;
  22484. return this._cache.position.equals(this.position)
  22485. && this._cache.upVector.equals(this.upVector)
  22486. && this.isSynchronizedWithParent();
  22487. };
  22488. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22489. var check = this._cache.mode === this.mode
  22490. && this._cache.minZ === this.minZ
  22491. && this._cache.maxZ === this.maxZ;
  22492. if (!check) {
  22493. return false;
  22494. }
  22495. var engine = this.getEngine();
  22496. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22497. check = this._cache.fov === this.fov
  22498. && this._cache.fovMode === this.fovMode
  22499. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22500. }
  22501. else {
  22502. check = this._cache.orthoLeft === this.orthoLeft
  22503. && this._cache.orthoRight === this.orthoRight
  22504. && this._cache.orthoBottom === this.orthoBottom
  22505. && this._cache.orthoTop === this.orthoTop
  22506. && this._cache.renderWidth === engine.getRenderWidth()
  22507. && this._cache.renderHeight === engine.getRenderHeight();
  22508. }
  22509. return check;
  22510. };
  22511. // Controls
  22512. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22513. };
  22514. Camera.prototype.detachControl = function (element) {
  22515. };
  22516. Camera.prototype.update = function () {
  22517. this._checkInputs();
  22518. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22519. this._updateRigCameras();
  22520. }
  22521. };
  22522. Camera.prototype._checkInputs = function () {
  22523. this.onAfterCheckInputsObservable.notifyObservers(this);
  22524. };
  22525. Object.defineProperty(Camera.prototype, "rigCameras", {
  22526. get: function () {
  22527. return this._rigCameras;
  22528. },
  22529. enumerable: true,
  22530. configurable: true
  22531. });
  22532. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22533. get: function () {
  22534. return this._rigPostProcess;
  22535. },
  22536. enumerable: true,
  22537. configurable: true
  22538. });
  22539. /**
  22540. * Internal, gets the first post proces.
  22541. * @returns the first post process to be run on this camera.
  22542. */
  22543. Camera.prototype._getFirstPostProcess = function () {
  22544. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22545. if (this._postProcesses[ppIndex] !== null) {
  22546. return this._postProcesses[ppIndex];
  22547. }
  22548. }
  22549. return null;
  22550. };
  22551. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22552. // invalidate framebuffer
  22553. var firstPostProcess = this._getFirstPostProcess();
  22554. if (firstPostProcess) {
  22555. firstPostProcess.markTextureDirty();
  22556. }
  22557. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22558. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22559. var cam = this._rigCameras[i];
  22560. var rigPostProcess = cam._rigPostProcess;
  22561. // for VR rig, there does not have to be a post process
  22562. if (rigPostProcess) {
  22563. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22564. if (isPass) {
  22565. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22566. cam.isIntermediate = this._postProcesses.length === 0;
  22567. }
  22568. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22569. rigPostProcess.markTextureDirty();
  22570. }
  22571. else {
  22572. cam._postProcesses = this._postProcesses.slice(0);
  22573. }
  22574. }
  22575. };
  22576. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22577. if (insertAt === void 0) { insertAt = null; }
  22578. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22579. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22580. return 0;
  22581. }
  22582. if (insertAt == null || insertAt < 0) {
  22583. this._postProcesses.push(postProcess);
  22584. }
  22585. else if (this._postProcesses[insertAt] === null) {
  22586. this._postProcesses[insertAt] = postProcess;
  22587. }
  22588. else {
  22589. this._postProcesses.splice(insertAt, 0, postProcess);
  22590. }
  22591. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22592. return this._postProcesses.indexOf(postProcess);
  22593. };
  22594. Camera.prototype.detachPostProcess = function (postProcess) {
  22595. var idx = this._postProcesses.indexOf(postProcess);
  22596. if (idx !== -1) {
  22597. this._postProcesses[idx] = null;
  22598. }
  22599. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22600. };
  22601. Camera.prototype.getWorldMatrix = function () {
  22602. if (this._isSynchronizedViewMatrix()) {
  22603. return this._worldMatrix;
  22604. }
  22605. // Getting the the view matrix will also compute the world matrix.
  22606. this.getViewMatrix();
  22607. return this._worldMatrix;
  22608. };
  22609. Camera.prototype._getViewMatrix = function () {
  22610. return BABYLON.Matrix.Identity();
  22611. };
  22612. Camera.prototype.getViewMatrix = function (force) {
  22613. if (!force && this._isSynchronizedViewMatrix()) {
  22614. return this._computedViewMatrix;
  22615. }
  22616. this.updateCache();
  22617. this._computedViewMatrix = this._getViewMatrix();
  22618. this._currentRenderId = this.getScene().getRenderId();
  22619. this._childRenderId = this._currentRenderId;
  22620. this._refreshFrustumPlanes = true;
  22621. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22622. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22623. }
  22624. this.onViewMatrixChangedObservable.notifyObservers(this);
  22625. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22626. return this._computedViewMatrix;
  22627. };
  22628. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22629. this._doNotComputeProjectionMatrix = true;
  22630. if (projection !== undefined) {
  22631. this._projectionMatrix = projection;
  22632. }
  22633. };
  22634. ;
  22635. Camera.prototype.unfreezeProjectionMatrix = function () {
  22636. this._doNotComputeProjectionMatrix = false;
  22637. };
  22638. ;
  22639. Camera.prototype.getProjectionMatrix = function (force) {
  22640. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22641. return this._projectionMatrix;
  22642. }
  22643. // Cache
  22644. this._cache.mode = this.mode;
  22645. this._cache.minZ = this.minZ;
  22646. this._cache.maxZ = this.maxZ;
  22647. // Matrix
  22648. this._refreshFrustumPlanes = true;
  22649. var engine = this.getEngine();
  22650. var scene = this.getScene();
  22651. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22652. this._cache.fov = this.fov;
  22653. this._cache.fovMode = this.fovMode;
  22654. this._cache.aspectRatio = engine.getAspectRatio(this);
  22655. if (this.minZ <= 0) {
  22656. this.minZ = 0.1;
  22657. }
  22658. if (scene.useRightHandedSystem) {
  22659. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22660. }
  22661. else {
  22662. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22663. }
  22664. }
  22665. else {
  22666. var halfWidth = engine.getRenderWidth() / 2.0;
  22667. var halfHeight = engine.getRenderHeight() / 2.0;
  22668. if (scene.useRightHandedSystem) {
  22669. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22670. }
  22671. else {
  22672. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22673. }
  22674. this._cache.orthoLeft = this.orthoLeft;
  22675. this._cache.orthoRight = this.orthoRight;
  22676. this._cache.orthoBottom = this.orthoBottom;
  22677. this._cache.orthoTop = this.orthoTop;
  22678. this._cache.renderWidth = engine.getRenderWidth();
  22679. this._cache.renderHeight = engine.getRenderHeight();
  22680. }
  22681. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22682. return this._projectionMatrix;
  22683. };
  22684. Camera.prototype.getTranformationMatrix = function () {
  22685. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22686. return this._transformMatrix;
  22687. };
  22688. Camera.prototype.updateFrustumPlanes = function () {
  22689. if (!this._refreshFrustumPlanes) {
  22690. return;
  22691. }
  22692. this.getTranformationMatrix();
  22693. if (!this._frustumPlanes) {
  22694. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22695. }
  22696. else {
  22697. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22698. }
  22699. this._refreshFrustumPlanes = false;
  22700. };
  22701. Camera.prototype.isInFrustum = function (target) {
  22702. this.updateFrustumPlanes();
  22703. return target.isInFrustum(this._frustumPlanes);
  22704. };
  22705. Camera.prototype.isCompletelyInFrustum = function (target) {
  22706. this.updateFrustumPlanes();
  22707. return target.isCompletelyInFrustum(this._frustumPlanes);
  22708. };
  22709. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22710. if (length === void 0) { length = 100; }
  22711. if (!transform) {
  22712. transform = this.getWorldMatrix();
  22713. }
  22714. if (!origin) {
  22715. origin = this.position;
  22716. }
  22717. var forward = new BABYLON.Vector3(0, 0, 1);
  22718. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22719. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22720. return new BABYLON.Ray(origin, direction, length);
  22721. };
  22722. /**
  22723. * Releases resources associated with this node.
  22724. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22725. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22726. */
  22727. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22728. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22729. // Observables
  22730. this.onViewMatrixChangedObservable.clear();
  22731. this.onProjectionMatrixChangedObservable.clear();
  22732. this.onAfterCheckInputsObservable.clear();
  22733. this.onRestoreStateObservable.clear();
  22734. // Inputs
  22735. if (this.inputs) {
  22736. this.inputs.clear();
  22737. }
  22738. // Animations
  22739. this.getScene().stopAnimation(this);
  22740. // Remove from scene
  22741. this.getScene().removeCamera(this);
  22742. while (this._rigCameras.length > 0) {
  22743. var camera = this._rigCameras.pop();
  22744. if (camera) {
  22745. camera.dispose();
  22746. }
  22747. }
  22748. // Postprocesses
  22749. if (this._rigPostProcess) {
  22750. this._rigPostProcess.dispose(this);
  22751. this._rigPostProcess = null;
  22752. this._postProcesses = [];
  22753. }
  22754. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22755. this._rigPostProcess = null;
  22756. this._postProcesses = [];
  22757. }
  22758. else {
  22759. var i = this._postProcesses.length;
  22760. while (--i >= 0) {
  22761. var postProcess = this._postProcesses[i];
  22762. if (postProcess) {
  22763. postProcess.dispose(this);
  22764. }
  22765. }
  22766. }
  22767. // Render targets
  22768. var i = this.customRenderTargets.length;
  22769. while (--i >= 0) {
  22770. this.customRenderTargets[i].dispose();
  22771. }
  22772. this.customRenderTargets = [];
  22773. // Active Meshes
  22774. this._activeMeshes.dispose();
  22775. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22776. };
  22777. Object.defineProperty(Camera.prototype, "leftCamera", {
  22778. // ---- Camera rigs section ----
  22779. get: function () {
  22780. if (this._rigCameras.length < 1) {
  22781. return null;
  22782. }
  22783. return this._rigCameras[0];
  22784. },
  22785. enumerable: true,
  22786. configurable: true
  22787. });
  22788. Object.defineProperty(Camera.prototype, "rightCamera", {
  22789. get: function () {
  22790. if (this._rigCameras.length < 2) {
  22791. return null;
  22792. }
  22793. return this._rigCameras[1];
  22794. },
  22795. enumerable: true,
  22796. configurable: true
  22797. });
  22798. Camera.prototype.getLeftTarget = function () {
  22799. if (this._rigCameras.length < 1) {
  22800. return null;
  22801. }
  22802. return this._rigCameras[0].getTarget();
  22803. };
  22804. Camera.prototype.getRightTarget = function () {
  22805. if (this._rigCameras.length < 2) {
  22806. return null;
  22807. }
  22808. return this._rigCameras[1].getTarget();
  22809. };
  22810. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22811. if (this.cameraRigMode === mode) {
  22812. return;
  22813. }
  22814. while (this._rigCameras.length > 0) {
  22815. var camera = this._rigCameras.pop();
  22816. if (camera) {
  22817. camera.dispose();
  22818. }
  22819. }
  22820. this.cameraRigMode = mode;
  22821. this._cameraRigParams = {};
  22822. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22823. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22824. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22825. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22826. // create the rig cameras, unless none
  22827. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22828. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22829. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22830. if (leftCamera && rightCamera) {
  22831. this._rigCameras.push(leftCamera);
  22832. this._rigCameras.push(rightCamera);
  22833. }
  22834. }
  22835. switch (this.cameraRigMode) {
  22836. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22837. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22838. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22839. break;
  22840. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22841. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22842. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22843. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22844. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22845. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22846. break;
  22847. case Camera.RIG_MODE_VR:
  22848. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22849. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22850. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22851. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22852. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22853. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22854. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22855. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22856. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22857. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22858. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22859. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22860. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22861. if (metrics.compensateDistortion) {
  22862. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22863. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22864. }
  22865. break;
  22866. case Camera.RIG_MODE_WEBVR:
  22867. if (rigParams.vrDisplay) {
  22868. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22869. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22870. //Left eye
  22871. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22872. this._rigCameras[0].setCameraRigParameter("left", true);
  22873. //leaving this for future reference
  22874. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22875. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22876. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22877. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22878. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22879. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22880. this._rigCameras[0].parent = this;
  22881. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22882. //Right eye
  22883. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22884. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22885. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22886. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22887. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22888. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22889. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22890. this._rigCameras[1].parent = this;
  22891. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22892. if (Camera.UseAlternateWebVRRendering) {
  22893. this._rigCameras[1]._skipRendering = true;
  22894. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22895. }
  22896. }
  22897. break;
  22898. }
  22899. this._cascadePostProcessesToRigCams();
  22900. this.update();
  22901. };
  22902. Camera.prototype._getVRProjectionMatrix = function () {
  22903. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22904. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22905. return this._projectionMatrix;
  22906. };
  22907. Camera.prototype._updateCameraRotationMatrix = function () {
  22908. //Here for WebVR
  22909. };
  22910. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22911. //Here for WebVR
  22912. };
  22913. /**
  22914. * This function MUST be overwritten by the different WebVR cameras available.
  22915. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22916. */
  22917. Camera.prototype._getWebVRProjectionMatrix = function () {
  22918. return BABYLON.Matrix.Identity();
  22919. };
  22920. /**
  22921. * This function MUST be overwritten by the different WebVR cameras available.
  22922. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22923. */
  22924. Camera.prototype._getWebVRViewMatrix = function () {
  22925. return BABYLON.Matrix.Identity();
  22926. };
  22927. Camera.prototype.setCameraRigParameter = function (name, value) {
  22928. if (!this._cameraRigParams) {
  22929. this._cameraRigParams = {};
  22930. }
  22931. this._cameraRigParams[name] = value;
  22932. //provisionnally:
  22933. if (name === "interaxialDistance") {
  22934. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22935. }
  22936. };
  22937. /**
  22938. * needs to be overridden by children so sub has required properties to be copied
  22939. */
  22940. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22941. return null;
  22942. };
  22943. /**
  22944. * May need to be overridden by children
  22945. */
  22946. Camera.prototype._updateRigCameras = function () {
  22947. for (var i = 0; i < this._rigCameras.length; i++) {
  22948. this._rigCameras[i].minZ = this.minZ;
  22949. this._rigCameras[i].maxZ = this.maxZ;
  22950. this._rigCameras[i].fov = this.fov;
  22951. }
  22952. // only update viewport when ANAGLYPH
  22953. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22954. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22955. }
  22956. };
  22957. Camera.prototype._setupInputs = function () {
  22958. };
  22959. Camera.prototype.serialize = function () {
  22960. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22961. // Type
  22962. serializationObject.type = this.getClassName();
  22963. // Parent
  22964. if (this.parent) {
  22965. serializationObject.parentId = this.parent.id;
  22966. }
  22967. if (this.inputs) {
  22968. this.inputs.serialize(serializationObject);
  22969. }
  22970. // Animations
  22971. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22972. serializationObject.ranges = this.serializeAnimationRanges();
  22973. return serializationObject;
  22974. };
  22975. Camera.prototype.clone = function (name) {
  22976. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22977. };
  22978. Camera.prototype.getDirection = function (localAxis) {
  22979. var result = BABYLON.Vector3.Zero();
  22980. this.getDirectionToRef(localAxis, result);
  22981. return result;
  22982. };
  22983. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22984. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22985. };
  22986. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22987. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22988. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22989. switch (type) {
  22990. case "ArcRotateCamera":
  22991. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22992. case "DeviceOrientationCamera":
  22993. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22994. case "FollowCamera":
  22995. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22996. case "ArcFollowCamera":
  22997. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22998. case "GamepadCamera":
  22999. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23000. case "TouchCamera":
  23001. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23002. case "VirtualJoysticksCamera":
  23003. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23004. case "WebVRFreeCamera":
  23005. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23006. case "WebVRGamepadCamera":
  23007. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23008. case "VRDeviceOrientationFreeCamera":
  23009. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23010. case "VRDeviceOrientationGamepadCamera":
  23011. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23012. case "AnaglyphArcRotateCamera":
  23013. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23014. case "AnaglyphFreeCamera":
  23015. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23016. case "AnaglyphGamepadCamera":
  23017. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23018. case "AnaglyphUniversalCamera":
  23019. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23020. case "StereoscopicArcRotateCamera":
  23021. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23022. case "StereoscopicFreeCamera":
  23023. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23024. case "StereoscopicGamepadCamera":
  23025. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23026. case "StereoscopicUniversalCamera":
  23027. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23028. case "FreeCamera": // Forcing Universal here
  23029. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23030. default: // Universal Camera is the default value
  23031. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23032. }
  23033. };
  23034. Camera.prototype.computeWorldMatrix = function () {
  23035. return this.getWorldMatrix();
  23036. };
  23037. Camera.Parse = function (parsedCamera, scene) {
  23038. var type = parsedCamera.type;
  23039. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23040. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23041. // Parent
  23042. if (parsedCamera.parentId) {
  23043. camera._waitingParentId = parsedCamera.parentId;
  23044. }
  23045. //If camera has an input manager, let it parse inputs settings
  23046. if (camera.inputs) {
  23047. camera.inputs.parse(parsedCamera);
  23048. camera._setupInputs();
  23049. }
  23050. if (camera.setPosition) { // need to force position
  23051. camera.position.copyFromFloats(0, 0, 0);
  23052. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23053. }
  23054. // Target
  23055. if (parsedCamera.target) {
  23056. if (camera.setTarget) {
  23057. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23058. }
  23059. }
  23060. // Apply 3d rig, when found
  23061. if (parsedCamera.cameraRigMode) {
  23062. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23063. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23064. }
  23065. // Animations
  23066. if (parsedCamera.animations) {
  23067. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23068. var parsedAnimation = parsedCamera.animations[animationIndex];
  23069. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23070. }
  23071. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23072. }
  23073. if (parsedCamera.autoAnimate) {
  23074. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23075. }
  23076. return camera;
  23077. };
  23078. // Statics
  23079. Camera._PERSPECTIVE_CAMERA = 0;
  23080. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23081. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23082. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23083. Camera._RIG_MODE_NONE = 0;
  23084. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23085. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23086. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23087. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23088. Camera._RIG_MODE_VR = 20;
  23089. Camera._RIG_MODE_WEBVR = 21;
  23090. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23091. Camera.UseAlternateWebVRRendering = false;
  23092. __decorate([
  23093. BABYLON.serializeAsVector3()
  23094. ], Camera.prototype, "position", void 0);
  23095. __decorate([
  23096. BABYLON.serializeAsVector3()
  23097. ], Camera.prototype, "upVector", void 0);
  23098. __decorate([
  23099. BABYLON.serialize()
  23100. ], Camera.prototype, "orthoLeft", void 0);
  23101. __decorate([
  23102. BABYLON.serialize()
  23103. ], Camera.prototype, "orthoRight", void 0);
  23104. __decorate([
  23105. BABYLON.serialize()
  23106. ], Camera.prototype, "orthoBottom", void 0);
  23107. __decorate([
  23108. BABYLON.serialize()
  23109. ], Camera.prototype, "orthoTop", void 0);
  23110. __decorate([
  23111. BABYLON.serialize()
  23112. ], Camera.prototype, "fov", void 0);
  23113. __decorate([
  23114. BABYLON.serialize()
  23115. ], Camera.prototype, "minZ", void 0);
  23116. __decorate([
  23117. BABYLON.serialize()
  23118. ], Camera.prototype, "maxZ", void 0);
  23119. __decorate([
  23120. BABYLON.serialize()
  23121. ], Camera.prototype, "inertia", void 0);
  23122. __decorate([
  23123. BABYLON.serialize()
  23124. ], Camera.prototype, "mode", void 0);
  23125. __decorate([
  23126. BABYLON.serialize()
  23127. ], Camera.prototype, "layerMask", void 0);
  23128. __decorate([
  23129. BABYLON.serialize()
  23130. ], Camera.prototype, "fovMode", void 0);
  23131. __decorate([
  23132. BABYLON.serialize()
  23133. ], Camera.prototype, "cameraRigMode", void 0);
  23134. __decorate([
  23135. BABYLON.serialize()
  23136. ], Camera.prototype, "interaxialDistance", void 0);
  23137. __decorate([
  23138. BABYLON.serialize()
  23139. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23140. return Camera;
  23141. }(BABYLON.Node));
  23142. BABYLON.Camera = Camera;
  23143. })(BABYLON || (BABYLON = {}));
  23144. //# sourceMappingURL=babylon.camera.js.map
  23145. var BABYLON;
  23146. (function (BABYLON) {
  23147. var RenderingManager = /** @class */ (function () {
  23148. function RenderingManager(scene) {
  23149. this._renderingGroups = new Array();
  23150. this._autoClearDepthStencil = {};
  23151. this._customOpaqueSortCompareFn = {};
  23152. this._customAlphaTestSortCompareFn = {};
  23153. this._customTransparentSortCompareFn = {};
  23154. this._renderinGroupInfo = null;
  23155. this._scene = scene;
  23156. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23157. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23158. }
  23159. }
  23160. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23161. if (depth === void 0) { depth = true; }
  23162. if (stencil === void 0) { stencil = true; }
  23163. if (this._depthStencilBufferAlreadyCleaned) {
  23164. return;
  23165. }
  23166. this._scene.getEngine().clear(null, false, depth, stencil);
  23167. this._depthStencilBufferAlreadyCleaned = true;
  23168. };
  23169. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23170. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23171. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23172. var info = null;
  23173. if (observable) {
  23174. if (!this._renderinGroupInfo) {
  23175. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23176. }
  23177. info = this._renderinGroupInfo;
  23178. info.scene = this._scene;
  23179. info.camera = this._scene.activeCamera;
  23180. }
  23181. // Dispatch sprites
  23182. if (renderSprites) {
  23183. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23184. var manager = this._scene.spriteManagers[index];
  23185. this.dispatchSprites(manager);
  23186. }
  23187. }
  23188. // Render
  23189. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23190. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23191. var renderingGroup = this._renderingGroups[index];
  23192. if (!renderingGroup && !observable)
  23193. continue;
  23194. var renderingGroupMask = 0;
  23195. // Fire PRECLEAR stage
  23196. if (observable && info) {
  23197. renderingGroupMask = Math.pow(2, index);
  23198. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23199. info.renderingGroupId = index;
  23200. observable.notifyObservers(info, renderingGroupMask);
  23201. }
  23202. // Clear depth/stencil if needed
  23203. if (RenderingManager.AUTOCLEAR) {
  23204. var autoClear = this._autoClearDepthStencil[index];
  23205. if (autoClear && autoClear.autoClear) {
  23206. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23207. }
  23208. }
  23209. if (observable && info) {
  23210. // Fire PREOPAQUE stage
  23211. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23212. observable.notifyObservers(info, renderingGroupMask);
  23213. // Fire PRETRANSPARENT stage
  23214. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23215. observable.notifyObservers(info, renderingGroupMask);
  23216. }
  23217. if (renderingGroup)
  23218. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23219. // Fire POSTTRANSPARENT stage
  23220. if (observable && info) {
  23221. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23222. observable.notifyObservers(info, renderingGroupMask);
  23223. }
  23224. }
  23225. };
  23226. RenderingManager.prototype.reset = function () {
  23227. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23228. var renderingGroup = this._renderingGroups[index];
  23229. if (renderingGroup) {
  23230. renderingGroup.prepare();
  23231. }
  23232. }
  23233. };
  23234. RenderingManager.prototype.dispose = function () {
  23235. this.freeRenderingGroups();
  23236. this._renderingGroups.length = 0;
  23237. };
  23238. /**
  23239. * Clear the info related to rendering groups preventing retention points during dispose.
  23240. */
  23241. RenderingManager.prototype.freeRenderingGroups = function () {
  23242. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23243. var renderingGroup = this._renderingGroups[index];
  23244. if (renderingGroup) {
  23245. renderingGroup.dispose();
  23246. }
  23247. }
  23248. };
  23249. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23250. if (this._renderingGroups[renderingGroupId] === undefined) {
  23251. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23252. }
  23253. };
  23254. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23255. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23256. this._prepareRenderingGroup(renderingGroupId);
  23257. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23258. };
  23259. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23260. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23261. this._prepareRenderingGroup(renderingGroupId);
  23262. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23263. };
  23264. /**
  23265. * @param subMesh The submesh to dispatch
  23266. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23267. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23268. */
  23269. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23270. if (mesh === undefined) {
  23271. mesh = subMesh.getMesh();
  23272. }
  23273. var renderingGroupId = mesh.renderingGroupId || 0;
  23274. this._prepareRenderingGroup(renderingGroupId);
  23275. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23276. };
  23277. /**
  23278. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23279. * This allowed control for front to back rendering or reversly depending of the special needs.
  23280. *
  23281. * @param renderingGroupId The rendering group id corresponding to its index
  23282. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23283. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23284. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23285. */
  23286. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23287. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23288. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23289. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23290. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23291. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23292. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23293. if (this._renderingGroups[renderingGroupId]) {
  23294. var group = this._renderingGroups[renderingGroupId];
  23295. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23296. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23297. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23298. }
  23299. };
  23300. /**
  23301. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23302. *
  23303. * @param renderingGroupId The rendering group id corresponding to its index
  23304. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23305. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23306. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23307. */
  23308. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23309. if (depth === void 0) { depth = true; }
  23310. if (stencil === void 0) { stencil = true; }
  23311. this._autoClearDepthStencil[renderingGroupId] = {
  23312. autoClear: autoClearDepthStencil,
  23313. depth: depth,
  23314. stencil: stencil
  23315. };
  23316. };
  23317. /**
  23318. * The max id used for rendering groups (not included)
  23319. */
  23320. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23321. /**
  23322. * The min id used for rendering groups (included)
  23323. */
  23324. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23325. /**
  23326. * Used to globally prevent autoclearing scenes.
  23327. */
  23328. RenderingManager.AUTOCLEAR = true;
  23329. return RenderingManager;
  23330. }());
  23331. BABYLON.RenderingManager = RenderingManager;
  23332. })(BABYLON || (BABYLON = {}));
  23333. //# sourceMappingURL=babylon.renderingManager.js.map
  23334. var BABYLON;
  23335. (function (BABYLON) {
  23336. var RenderingGroup = /** @class */ (function () {
  23337. /**
  23338. * Creates a new rendering group.
  23339. * @param index The rendering group index
  23340. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23341. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23342. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23343. */
  23344. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23345. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23346. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23347. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23348. this.index = index;
  23349. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23350. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23351. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23352. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23353. this._particleSystems = new BABYLON.SmartArray(256);
  23354. this._spriteManagers = new BABYLON.SmartArray(256);
  23355. this._edgesRenderers = new BABYLON.SmartArray(16);
  23356. this._scene = scene;
  23357. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23358. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23359. this.transparentSortCompareFn = transparentSortCompareFn;
  23360. }
  23361. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23362. /**
  23363. * Set the opaque sort comparison function.
  23364. * If null the sub meshes will be render in the order they were created
  23365. */
  23366. set: function (value) {
  23367. this._opaqueSortCompareFn = value;
  23368. if (value) {
  23369. this._renderOpaque = this.renderOpaqueSorted;
  23370. }
  23371. else {
  23372. this._renderOpaque = RenderingGroup.renderUnsorted;
  23373. }
  23374. },
  23375. enumerable: true,
  23376. configurable: true
  23377. });
  23378. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23379. /**
  23380. * Set the alpha test sort comparison function.
  23381. * If null the sub meshes will be render in the order they were created
  23382. */
  23383. set: function (value) {
  23384. this._alphaTestSortCompareFn = value;
  23385. if (value) {
  23386. this._renderAlphaTest = this.renderAlphaTestSorted;
  23387. }
  23388. else {
  23389. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23390. }
  23391. },
  23392. enumerable: true,
  23393. configurable: true
  23394. });
  23395. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23396. /**
  23397. * Set the transparent sort comparison function.
  23398. * If null the sub meshes will be render in the order they were created
  23399. */
  23400. set: function (value) {
  23401. if (value) {
  23402. this._transparentSortCompareFn = value;
  23403. }
  23404. else {
  23405. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23406. }
  23407. this._renderTransparent = this.renderTransparentSorted;
  23408. },
  23409. enumerable: true,
  23410. configurable: true
  23411. });
  23412. /**
  23413. * Render all the sub meshes contained in the group.
  23414. * @param customRenderFunction Used to override the default render behaviour of the group.
  23415. * @returns true if rendered some submeshes.
  23416. */
  23417. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23418. if (customRenderFunction) {
  23419. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23420. return;
  23421. }
  23422. var engine = this._scene.getEngine();
  23423. // Depth only
  23424. if (this._depthOnlySubMeshes.length !== 0) {
  23425. engine.setColorWrite(false);
  23426. this._renderAlphaTest(this._depthOnlySubMeshes);
  23427. engine.setColorWrite(true);
  23428. }
  23429. // Opaque
  23430. if (this._opaqueSubMeshes.length !== 0) {
  23431. this._renderOpaque(this._opaqueSubMeshes);
  23432. }
  23433. // Alpha test
  23434. if (this._alphaTestSubMeshes.length !== 0) {
  23435. this._renderAlphaTest(this._alphaTestSubMeshes);
  23436. }
  23437. var stencilState = engine.getStencilBuffer();
  23438. engine.setStencilBuffer(false);
  23439. // Sprites
  23440. if (renderSprites) {
  23441. this._renderSprites();
  23442. }
  23443. // Particles
  23444. if (renderParticles) {
  23445. this._renderParticles(activeMeshes);
  23446. }
  23447. if (this.onBeforeTransparentRendering) {
  23448. this.onBeforeTransparentRendering();
  23449. }
  23450. // Transparent
  23451. if (this._transparentSubMeshes.length !== 0) {
  23452. this._renderTransparent(this._transparentSubMeshes);
  23453. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23454. }
  23455. // Set back stencil to false in case it changes before the edge renderer.
  23456. engine.setStencilBuffer(false);
  23457. // Edges
  23458. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23459. this._edgesRenderers.data[edgesRendererIndex].render();
  23460. }
  23461. // Restore Stencil state.
  23462. engine.setStencilBuffer(stencilState);
  23463. };
  23464. /**
  23465. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23466. * @param subMeshes The submeshes to render
  23467. */
  23468. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23469. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23470. };
  23471. /**
  23472. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23473. * @param subMeshes The submeshes to render
  23474. */
  23475. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23476. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23477. };
  23478. /**
  23479. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23480. * @param subMeshes The submeshes to render
  23481. */
  23482. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23483. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23484. };
  23485. /**
  23486. * Renders the submeshes in a specified order.
  23487. * @param subMeshes The submeshes to sort before render
  23488. * @param sortCompareFn The comparison function use to sort
  23489. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23490. * @param transparent Specifies to activate blending if true
  23491. */
  23492. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23493. var subIndex = 0;
  23494. var subMesh;
  23495. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23496. for (; subIndex < subMeshes.length; subIndex++) {
  23497. subMesh = subMeshes.data[subIndex];
  23498. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23499. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23500. }
  23501. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23502. if (sortCompareFn) {
  23503. sortedArray.sort(sortCompareFn);
  23504. }
  23505. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23506. subMesh = sortedArray[subIndex];
  23507. if (transparent) {
  23508. var material = subMesh.getMaterial();
  23509. if (material && material.needDepthPrePass) {
  23510. var engine = material.getScene().getEngine();
  23511. engine.setColorWrite(false);
  23512. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23513. subMesh.render(false);
  23514. engine.setColorWrite(true);
  23515. }
  23516. }
  23517. subMesh.render(transparent);
  23518. }
  23519. };
  23520. /**
  23521. * Renders the submeshes in the order they were dispatched (no sort applied).
  23522. * @param subMeshes The submeshes to render
  23523. */
  23524. RenderingGroup.renderUnsorted = function (subMeshes) {
  23525. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23526. var submesh = subMeshes.data[subIndex];
  23527. submesh.render(false);
  23528. }
  23529. };
  23530. /**
  23531. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23532. * are rendered back to front if in the same alpha index.
  23533. *
  23534. * @param a The first submesh
  23535. * @param b The second submesh
  23536. * @returns The result of the comparison
  23537. */
  23538. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23539. // Alpha index first
  23540. if (a._alphaIndex > b._alphaIndex) {
  23541. return 1;
  23542. }
  23543. if (a._alphaIndex < b._alphaIndex) {
  23544. return -1;
  23545. }
  23546. // Then distance to camera
  23547. return RenderingGroup.backToFrontSortCompare(a, b);
  23548. };
  23549. /**
  23550. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23551. * are rendered back to front.
  23552. *
  23553. * @param a The first submesh
  23554. * @param b The second submesh
  23555. * @returns The result of the comparison
  23556. */
  23557. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23558. // Then distance to camera
  23559. if (a._distanceToCamera < b._distanceToCamera) {
  23560. return 1;
  23561. }
  23562. if (a._distanceToCamera > b._distanceToCamera) {
  23563. return -1;
  23564. }
  23565. return 0;
  23566. };
  23567. /**
  23568. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23569. * are rendered front to back (prevent overdraw).
  23570. *
  23571. * @param a The first submesh
  23572. * @param b The second submesh
  23573. * @returns The result of the comparison
  23574. */
  23575. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23576. // Then distance to camera
  23577. if (a._distanceToCamera < b._distanceToCamera) {
  23578. return -1;
  23579. }
  23580. if (a._distanceToCamera > b._distanceToCamera) {
  23581. return 1;
  23582. }
  23583. return 0;
  23584. };
  23585. /**
  23586. * Resets the different lists of submeshes to prepare a new frame.
  23587. */
  23588. RenderingGroup.prototype.prepare = function () {
  23589. this._opaqueSubMeshes.reset();
  23590. this._transparentSubMeshes.reset();
  23591. this._alphaTestSubMeshes.reset();
  23592. this._depthOnlySubMeshes.reset();
  23593. this._particleSystems.reset();
  23594. this._spriteManagers.reset();
  23595. this._edgesRenderers.reset();
  23596. };
  23597. RenderingGroup.prototype.dispose = function () {
  23598. this._opaqueSubMeshes.dispose();
  23599. this._transparentSubMeshes.dispose();
  23600. this._alphaTestSubMeshes.dispose();
  23601. this._depthOnlySubMeshes.dispose();
  23602. this._particleSystems.dispose();
  23603. this._spriteManagers.dispose();
  23604. this._edgesRenderers.dispose();
  23605. };
  23606. /**
  23607. * Inserts the submesh in its correct queue depending on its material.
  23608. * @param subMesh The submesh to dispatch
  23609. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23610. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23611. */
  23612. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23613. // Get mesh and materials if not provided
  23614. if (mesh === undefined) {
  23615. mesh = subMesh.getMesh();
  23616. }
  23617. if (material === undefined) {
  23618. material = subMesh.getMaterial();
  23619. }
  23620. if (material === null || material === undefined) {
  23621. return;
  23622. }
  23623. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23624. this._transparentSubMeshes.push(subMesh);
  23625. }
  23626. else if (material.needAlphaTesting()) { // Alpha test
  23627. if (material.needDepthPrePass) {
  23628. this._depthOnlySubMeshes.push(subMesh);
  23629. }
  23630. this._alphaTestSubMeshes.push(subMesh);
  23631. }
  23632. else {
  23633. if (material.needDepthPrePass) {
  23634. this._depthOnlySubMeshes.push(subMesh);
  23635. }
  23636. this._opaqueSubMeshes.push(subMesh); // Opaque
  23637. }
  23638. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23639. this._edgesRenderers.push(mesh._edgesRenderer);
  23640. }
  23641. };
  23642. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23643. this._spriteManagers.push(spriteManager);
  23644. };
  23645. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23646. this._particleSystems.push(particleSystem);
  23647. };
  23648. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23649. if (this._particleSystems.length === 0) {
  23650. return;
  23651. }
  23652. // Particles
  23653. var activeCamera = this._scene.activeCamera;
  23654. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23655. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23656. var particleSystem = this._particleSystems.data[particleIndex];
  23657. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23658. continue;
  23659. }
  23660. var emitter = particleSystem.emitter;
  23661. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23662. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23663. }
  23664. }
  23665. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23666. };
  23667. RenderingGroup.prototype._renderSprites = function () {
  23668. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23669. return;
  23670. }
  23671. // Sprites
  23672. var activeCamera = this._scene.activeCamera;
  23673. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23674. for (var id = 0; id < this._spriteManagers.length; id++) {
  23675. var spriteManager = this._spriteManagers.data[id];
  23676. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23677. spriteManager.render();
  23678. }
  23679. }
  23680. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23681. };
  23682. return RenderingGroup;
  23683. }());
  23684. BABYLON.RenderingGroup = RenderingGroup;
  23685. })(BABYLON || (BABYLON = {}));
  23686. //# sourceMappingURL=babylon.renderingGroup.js.map
  23687. var BABYLON;
  23688. (function (BABYLON) {
  23689. /** @hidden */
  23690. var ClickInfo = /** @class */ (function () {
  23691. function ClickInfo() {
  23692. this._singleClick = false;
  23693. this._doubleClick = false;
  23694. this._hasSwiped = false;
  23695. this._ignore = false;
  23696. }
  23697. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23698. get: function () {
  23699. return this._singleClick;
  23700. },
  23701. set: function (b) {
  23702. this._singleClick = b;
  23703. },
  23704. enumerable: true,
  23705. configurable: true
  23706. });
  23707. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23708. get: function () {
  23709. return this._doubleClick;
  23710. },
  23711. set: function (b) {
  23712. this._doubleClick = b;
  23713. },
  23714. enumerable: true,
  23715. configurable: true
  23716. });
  23717. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23718. get: function () {
  23719. return this._hasSwiped;
  23720. },
  23721. set: function (b) {
  23722. this._hasSwiped = b;
  23723. },
  23724. enumerable: true,
  23725. configurable: true
  23726. });
  23727. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23728. get: function () {
  23729. return this._ignore;
  23730. },
  23731. set: function (b) {
  23732. this._ignore = b;
  23733. },
  23734. enumerable: true,
  23735. configurable: true
  23736. });
  23737. return ClickInfo;
  23738. }());
  23739. /**
  23740. * This class is used by the onRenderingGroupObservable
  23741. */
  23742. var RenderingGroupInfo = /** @class */ (function () {
  23743. function RenderingGroupInfo() {
  23744. }
  23745. /**
  23746. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23747. * This stage will be fired no matter what
  23748. */
  23749. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23750. /**
  23751. * Called before opaque object are rendered.
  23752. * This stage will be fired only if there's 3D Opaque content to render
  23753. */
  23754. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23755. /**
  23756. * Called after the opaque objects are rendered and before the transparent ones
  23757. * This stage will be fired only if there's 3D transparent content to render
  23758. */
  23759. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23760. /**
  23761. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23762. * This stage will be fired no matter what
  23763. */
  23764. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23765. return RenderingGroupInfo;
  23766. }());
  23767. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23768. /**
  23769. * Represents a scene to be rendered by the engine.
  23770. * @see http://doc.babylonjs.com/features/scene
  23771. */
  23772. var Scene = /** @class */ (function () {
  23773. /**
  23774. * Creates a new Scene
  23775. * @param engine defines the engine to use to render this scene
  23776. */
  23777. function Scene(engine) {
  23778. // Members
  23779. /**
  23780. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23781. */
  23782. this.autoClear = true;
  23783. /**
  23784. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23785. */
  23786. this.autoClearDepthAndStencil = true;
  23787. /**
  23788. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23789. */
  23790. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23791. /**
  23792. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23793. */
  23794. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23795. this._forceWireframe = false;
  23796. this._forcePointsCloud = false;
  23797. /**
  23798. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23799. */
  23800. this.forceShowBoundingBoxes = false;
  23801. /**
  23802. * Gets or sets a boolean indicating if animations are enabled
  23803. */
  23804. this.animationsEnabled = true;
  23805. this._animationPropertiesOverride = null;
  23806. /**
  23807. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23808. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23809. */
  23810. this.useConstantAnimationDeltaTime = false;
  23811. /**
  23812. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23813. * Please note that it requires to run a ray cast through the scene on every frame
  23814. */
  23815. this.constantlyUpdateMeshUnderPointer = false;
  23816. /**
  23817. * Defines the HTML cursor to use when hovering over interactive elements
  23818. */
  23819. this.hoverCursor = "pointer";
  23820. /**
  23821. * Defines the HTML default cursor to use (empty by default)
  23822. */
  23823. this.defaultCursor = "";
  23824. /**
  23825. * This is used to call preventDefault() on pointer down
  23826. * in order to block unwanted artifacts like system double clicks
  23827. */
  23828. this.preventDefaultOnPointerDown = true;
  23829. // Metadata
  23830. /**
  23831. * Gets or sets user defined metadata
  23832. */
  23833. this.metadata = null;
  23834. /**
  23835. * Use this array to add regular expressions used to disable offline support for specific urls
  23836. */
  23837. this.disableOfflineSupportExceptionRules = new Array();
  23838. /**
  23839. * An event triggered when the scene is disposed.
  23840. */
  23841. this.onDisposeObservable = new BABYLON.Observable();
  23842. this._onDisposeObserver = null;
  23843. /**
  23844. * An event triggered before rendering the scene (right after animations and physics)
  23845. */
  23846. this.onBeforeRenderObservable = new BABYLON.Observable();
  23847. this._onBeforeRenderObserver = null;
  23848. /**
  23849. * An event triggered after rendering the scene
  23850. */
  23851. this.onAfterRenderObservable = new BABYLON.Observable();
  23852. this._onAfterRenderObserver = null;
  23853. /**
  23854. * An event triggered before animating the scene
  23855. */
  23856. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23857. /**
  23858. * An event triggered after animations processing
  23859. */
  23860. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23861. /**
  23862. * An event triggered before draw calls are ready to be sent
  23863. */
  23864. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23865. /**
  23866. * An event triggered after draw calls have been sent
  23867. */
  23868. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23869. /**
  23870. * An event triggered when physic simulation is about to be run
  23871. */
  23872. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23873. /**
  23874. * An event triggered when physic simulation has been done
  23875. */
  23876. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23877. /**
  23878. * An event triggered when the scene is ready
  23879. */
  23880. this.onReadyObservable = new BABYLON.Observable();
  23881. /**
  23882. * An event triggered before rendering a camera
  23883. */
  23884. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23885. this._onBeforeCameraRenderObserver = null;
  23886. /**
  23887. * An event triggered after rendering a camera
  23888. */
  23889. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23890. this._onAfterCameraRenderObserver = null;
  23891. /**
  23892. * An event triggered when active meshes evaluation is about to start
  23893. */
  23894. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23895. /**
  23896. * An event triggered when active meshes evaluation is done
  23897. */
  23898. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23899. /**
  23900. * An event triggered when particles rendering is about to start
  23901. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23902. */
  23903. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23904. /**
  23905. * An event triggered when particles rendering is done
  23906. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23907. */
  23908. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23909. /**
  23910. * An event triggered when sprites rendering is about to start
  23911. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23912. */
  23913. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23914. /**
  23915. * An event triggered when sprites rendering is done
  23916. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23917. */
  23918. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23919. /**
  23920. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23921. */
  23922. this.onDataLoadedObservable = new BABYLON.Observable();
  23923. /**
  23924. * An event triggered when a camera is created
  23925. */
  23926. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23927. /**
  23928. * An event triggered when a camera is removed
  23929. */
  23930. this.onCameraRemovedObservable = new BABYLON.Observable();
  23931. /**
  23932. * An event triggered when a light is created
  23933. */
  23934. this.onNewLightAddedObservable = new BABYLON.Observable();
  23935. /**
  23936. * An event triggered when a light is removed
  23937. */
  23938. this.onLightRemovedObservable = new BABYLON.Observable();
  23939. /**
  23940. * An event triggered when a geometry is created
  23941. */
  23942. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23943. /**
  23944. * An event triggered when a geometry is removed
  23945. */
  23946. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23947. /**
  23948. * An event triggered when a transform node is created
  23949. */
  23950. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23951. /**
  23952. * An event triggered when a transform node is removed
  23953. */
  23954. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23955. /**
  23956. * An event triggered when a mesh is created
  23957. */
  23958. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23959. /**
  23960. * An event triggered when a mesh is removed
  23961. */
  23962. this.onMeshRemovedObservable = new BABYLON.Observable();
  23963. /**
  23964. * An event triggered when render targets are about to be rendered
  23965. * Can happen multiple times per frame.
  23966. */
  23967. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23968. /**
  23969. * An event triggered when render targets were rendered.
  23970. * Can happen multiple times per frame.
  23971. */
  23972. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23973. /**
  23974. * An event triggered before calculating deterministic simulation step
  23975. */
  23976. this.onBeforeStepObservable = new BABYLON.Observable();
  23977. /**
  23978. * An event triggered after calculating deterministic simulation step
  23979. */
  23980. this.onAfterStepObservable = new BABYLON.Observable();
  23981. /**
  23982. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23983. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23984. * 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)
  23985. */
  23986. this.onRenderingGroupObservable = new BABYLON.Observable();
  23987. // Animations
  23988. /**
  23989. * Gets a list of Animations associated with the scene
  23990. */
  23991. this.animations = [];
  23992. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23993. /**
  23994. * 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).
  23995. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23996. */
  23997. this.onPrePointerObservable = new BABYLON.Observable();
  23998. /**
  23999. * Observable event triggered each time an input event is received from the rendering canvas
  24000. */
  24001. this.onPointerObservable = new BABYLON.Observable();
  24002. this._meshPickProceed = false;
  24003. this._currentPickResult = null;
  24004. this._previousPickResult = null;
  24005. this._totalPointersPressed = 0;
  24006. this._doubleClickOccured = false;
  24007. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24008. this.cameraToUseForPointers = null;
  24009. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24010. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24011. this._startingPointerTime = 0;
  24012. this._previousStartingPointerTime = 0;
  24013. this._pointerCaptures = {};
  24014. // Deterministic lockstep
  24015. this._timeAccumulator = 0;
  24016. this._currentStepId = 0;
  24017. this._currentInternalStep = 0;
  24018. // Keyboard
  24019. /**
  24020. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24021. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24022. */
  24023. this.onPreKeyboardObservable = new BABYLON.Observable();
  24024. /**
  24025. * Observable event triggered each time an keyboard event is received from the hosting window
  24026. */
  24027. this.onKeyboardObservable = new BABYLON.Observable();
  24028. // Coordinates system
  24029. this._useRightHandedSystem = false;
  24030. // Fog
  24031. this._fogEnabled = true;
  24032. this._fogMode = Scene.FOGMODE_NONE;
  24033. /**
  24034. * Gets or sets the fog color to use
  24035. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24036. */
  24037. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24038. /**
  24039. * Gets or sets the fog density to use
  24040. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24041. */
  24042. this.fogDensity = 0.1;
  24043. /**
  24044. * Gets or sets the fog start distance to use
  24045. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24046. */
  24047. this.fogStart = 0;
  24048. /**
  24049. * Gets or sets the fog end distance to use
  24050. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24051. */
  24052. this.fogEnd = 1000.0;
  24053. // Lights
  24054. this._shadowsEnabled = true;
  24055. this._lightsEnabled = true;
  24056. /**
  24057. * All of the lights added to this scene
  24058. * @see http://doc.babylonjs.com/babylon101/lights
  24059. */
  24060. this.lights = new Array();
  24061. // Cameras
  24062. /** All of the cameras added to this scene.
  24063. * @see http://doc.babylonjs.com/babylon101/cameras
  24064. */
  24065. this.cameras = new Array();
  24066. /** All of the active cameras added to this scene. */
  24067. this.activeCameras = new Array();
  24068. // Meshes
  24069. /**
  24070. * All of the tranform nodes added to this scene
  24071. * @see http://doc.babylonjs.com/how_to/transformnode
  24072. */
  24073. this.transformNodes = new Array();
  24074. /**
  24075. * All of the (abstract) meshes added to this scene
  24076. */
  24077. this.meshes = new Array();
  24078. /**
  24079. * All of the animation groups added to this scene
  24080. * @see http://doc.babylonjs.com/how_to/group
  24081. */
  24082. this.animationGroups = new Array();
  24083. // Geometries
  24084. this._geometries = new Array();
  24085. /**
  24086. * All of the materials added to this scene
  24087. * @see http://doc.babylonjs.com/babylon101/materials
  24088. */
  24089. this.materials = new Array();
  24090. /**
  24091. * All of the multi-materials added to this scene
  24092. * @see http://doc.babylonjs.com/how_to/multi_materials
  24093. */
  24094. this.multiMaterials = new Array();
  24095. // Textures
  24096. this._texturesEnabled = true;
  24097. /**
  24098. * All of the textures added to this scene
  24099. */
  24100. this.textures = new Array();
  24101. // Particles
  24102. /**
  24103. * Gets or sets a boolean indicating if particles are enabled on this scene
  24104. */
  24105. this.particlesEnabled = true;
  24106. /**
  24107. * All of the particle systems added to this scene
  24108. * @see http://doc.babylonjs.com/babylon101/particles
  24109. */
  24110. this.particleSystems = new Array();
  24111. // Sprites
  24112. /**
  24113. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24114. */
  24115. this.spritesEnabled = true;
  24116. /**
  24117. * All of the sprite managers added to this scene
  24118. * @see http://doc.babylonjs.com/babylon101/sprites
  24119. */
  24120. this.spriteManagers = new Array();
  24121. /**
  24122. * The list of layers (background and foreground) of the scene
  24123. */
  24124. this.layers = new Array();
  24125. /**
  24126. * The list of effect layers (highlights/glow) added to the scene
  24127. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24128. * @see http://doc.babylonjs.com/how_to/glow_layer
  24129. */
  24130. this.effectLayers = new Array();
  24131. // Skeletons
  24132. this._skeletonsEnabled = true;
  24133. /**
  24134. * The list of skeletons added to the scene
  24135. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24136. */
  24137. this.skeletons = new Array();
  24138. // Morph targets
  24139. /**
  24140. * The list of morph target managers added to the scene
  24141. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24142. */
  24143. this.morphTargetManagers = new Array();
  24144. // Lens flares
  24145. /**
  24146. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24147. */
  24148. this.lensFlaresEnabled = true;
  24149. /**
  24150. * The list of lens flare system added to the scene
  24151. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24152. */
  24153. this.lensFlareSystems = new Array();
  24154. // Collisions
  24155. /**
  24156. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24157. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24158. */
  24159. this.collisionsEnabled = true;
  24160. /**
  24161. * Defines the gravity applied to this scene (used only for collisions)
  24162. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24163. */
  24164. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24165. // Postprocesses
  24166. /**
  24167. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24168. */
  24169. this.postProcessesEnabled = true;
  24170. /**
  24171. * The list of postprocesses added to the scene
  24172. */
  24173. this.postProcesses = new Array();
  24174. // Customs render targets
  24175. /**
  24176. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24177. */
  24178. this.renderTargetsEnabled = true;
  24179. /**
  24180. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24181. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24182. */
  24183. this.dumpNextRenderTargets = false;
  24184. /**
  24185. * The list of user defined render targets added to the scene
  24186. */
  24187. this.customRenderTargets = new Array();
  24188. /**
  24189. * Gets the list of meshes imported to the scene through SceneLoader
  24190. */
  24191. this.importedMeshesFiles = new Array();
  24192. // Probes
  24193. /**
  24194. * Gets or sets a boolean indicating if probes are enabled on this scene
  24195. */
  24196. this.probesEnabled = true;
  24197. /**
  24198. * The list of reflection probes added to the scene
  24199. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24200. */
  24201. this.reflectionProbes = new Array();
  24202. /** @hidden */
  24203. this._actionManagers = new Array();
  24204. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24205. // Procedural textures
  24206. /**
  24207. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24208. */
  24209. this.proceduralTexturesEnabled = true;
  24210. /**
  24211. * The list of procedural textures added to the scene
  24212. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24213. */
  24214. this.proceduralTextures = new Array();
  24215. /**
  24216. * The list of sound tracks added to the scene
  24217. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24218. */
  24219. this.soundTracks = new Array();
  24220. this._audioEnabled = true;
  24221. this._headphone = false;
  24222. // Performance counters
  24223. this._totalVertices = new BABYLON.PerfCounter();
  24224. /** @hidden */
  24225. this._activeIndices = new BABYLON.PerfCounter();
  24226. /** @hidden */
  24227. this._activeParticles = new BABYLON.PerfCounter();
  24228. /** @hidden */
  24229. this._activeBones = new BABYLON.PerfCounter();
  24230. this._animationTime = 0;
  24231. /**
  24232. * Gets or sets a general scale for animation speed
  24233. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24234. */
  24235. this.animationTimeScale = 1;
  24236. this._renderId = 0;
  24237. this._executeWhenReadyTimeoutId = -1;
  24238. this._intermediateRendering = false;
  24239. this._viewUpdateFlag = -1;
  24240. this._projectionUpdateFlag = -1;
  24241. this._alternateViewUpdateFlag = -1;
  24242. this._alternateProjectionUpdateFlag = -1;
  24243. /** @hidden */
  24244. this._toBeDisposed = new BABYLON.SmartArray(256);
  24245. this._activeRequests = new Array();
  24246. this._pendingData = new Array();
  24247. this._isDisposed = false;
  24248. /**
  24249. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24250. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24251. */
  24252. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24253. this._activeMeshes = new BABYLON.SmartArray(256);
  24254. this._processedMaterials = new BABYLON.SmartArray(256);
  24255. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24256. /** @hidden */
  24257. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24258. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24259. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24260. /** @hidden */
  24261. this._activeAnimatables = new Array();
  24262. this._transformMatrix = BABYLON.Matrix.Zero();
  24263. this._useAlternateCameraConfiguration = false;
  24264. this._alternateRendering = false;
  24265. /**
  24266. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24267. * This is useful if there are more lights that the maximum simulteanous authorized
  24268. */
  24269. this.requireLightSorting = false;
  24270. this._depthRenderer = {};
  24271. this._activeMeshesFrozen = false;
  24272. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24273. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24274. this._engine.scenes.push(this);
  24275. this._uid = null;
  24276. this._renderingManager = new BABYLON.RenderingManager(this);
  24277. if (BABYLON.PostProcessManager) {
  24278. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24279. }
  24280. if (BABYLON.OutlineRenderer) {
  24281. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24282. }
  24283. if (BABYLON.Tools.IsWindowObjectExist()) {
  24284. this.attachControl();
  24285. }
  24286. //simplification queue
  24287. if (BABYLON.SimplificationQueue) {
  24288. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24289. }
  24290. //collision coordinator initialization. For now legacy per default.
  24291. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24292. // Uniform Buffer
  24293. this._createUbo();
  24294. // Default Image processing definition
  24295. if (BABYLON.ImageProcessingConfiguration) {
  24296. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24297. }
  24298. }
  24299. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24300. /** The fog is deactivated */
  24301. get: function () {
  24302. return Scene._FOGMODE_NONE;
  24303. },
  24304. enumerable: true,
  24305. configurable: true
  24306. });
  24307. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24308. /** The fog density is following an exponential function */
  24309. get: function () {
  24310. return Scene._FOGMODE_EXP;
  24311. },
  24312. enumerable: true,
  24313. configurable: true
  24314. });
  24315. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24316. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24317. get: function () {
  24318. return Scene._FOGMODE_EXP2;
  24319. },
  24320. enumerable: true,
  24321. configurable: true
  24322. });
  24323. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24324. /** The fog density is following a linear function. */
  24325. get: function () {
  24326. return Scene._FOGMODE_LINEAR;
  24327. },
  24328. enumerable: true,
  24329. configurable: true
  24330. });
  24331. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24332. /**
  24333. * Texture used in all pbr material as the reflection texture.
  24334. * As in the majority of the scene they are the same (exception for multi room and so on),
  24335. * this is easier to reference from here than from all the materials.
  24336. */
  24337. get: function () {
  24338. return this._environmentTexture;
  24339. },
  24340. /**
  24341. * Texture used in all pbr material as the reflection texture.
  24342. * As in the majority of the scene they are the same (exception for multi room and so on),
  24343. * this is easier to set here than in all the materials.
  24344. */
  24345. set: function (value) {
  24346. if (this._environmentTexture === value) {
  24347. return;
  24348. }
  24349. this._environmentTexture = value;
  24350. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24351. },
  24352. enumerable: true,
  24353. configurable: true
  24354. });
  24355. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24356. /**
  24357. * Default image processing configuration used either in the rendering
  24358. * Forward main pass or through the imageProcessingPostProcess if present.
  24359. * As in the majority of the scene they are the same (exception for multi camera),
  24360. * this is easier to reference from here than from all the materials and post process.
  24361. *
  24362. * No setter as we it is a shared configuration, you can set the values instead.
  24363. */
  24364. get: function () {
  24365. return this._imageProcessingConfiguration;
  24366. },
  24367. enumerable: true,
  24368. configurable: true
  24369. });
  24370. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24371. get: function () {
  24372. return this._forceWireframe;
  24373. },
  24374. /**
  24375. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24376. */
  24377. set: function (value) {
  24378. if (this._forceWireframe === value) {
  24379. return;
  24380. }
  24381. this._forceWireframe = value;
  24382. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24383. },
  24384. enumerable: true,
  24385. configurable: true
  24386. });
  24387. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24388. get: function () {
  24389. return this._forcePointsCloud;
  24390. },
  24391. /**
  24392. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24393. */
  24394. set: function (value) {
  24395. if (this._forcePointsCloud === value) {
  24396. return;
  24397. }
  24398. this._forcePointsCloud = value;
  24399. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24405. /**
  24406. * Gets or sets the animation properties override
  24407. */
  24408. get: function () {
  24409. return this._animationPropertiesOverride;
  24410. },
  24411. set: function (value) {
  24412. this._animationPropertiesOverride = value;
  24413. },
  24414. enumerable: true,
  24415. configurable: true
  24416. });
  24417. Object.defineProperty(Scene.prototype, "onDispose", {
  24418. /** Sets a function to be executed when this scene is disposed. */
  24419. set: function (callback) {
  24420. if (this._onDisposeObserver) {
  24421. this.onDisposeObservable.remove(this._onDisposeObserver);
  24422. }
  24423. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24424. },
  24425. enumerable: true,
  24426. configurable: true
  24427. });
  24428. Object.defineProperty(Scene.prototype, "beforeRender", {
  24429. /** Sets a function to be executed before rendering this scene */
  24430. set: function (callback) {
  24431. if (this._onBeforeRenderObserver) {
  24432. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24433. }
  24434. if (callback) {
  24435. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24436. }
  24437. },
  24438. enumerable: true,
  24439. configurable: true
  24440. });
  24441. Object.defineProperty(Scene.prototype, "afterRender", {
  24442. /** Sets a function to be executed after rendering this scene */
  24443. set: function (callback) {
  24444. if (this._onAfterRenderObserver) {
  24445. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24446. }
  24447. if (callback) {
  24448. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24449. }
  24450. },
  24451. enumerable: true,
  24452. configurable: true
  24453. });
  24454. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24455. /** Sets a function to be executed before rendering a camera*/
  24456. set: function (callback) {
  24457. if (this._onBeforeCameraRenderObserver) {
  24458. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24459. }
  24460. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24461. },
  24462. enumerable: true,
  24463. configurable: true
  24464. });
  24465. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24466. /** Sets a function to be executed after rendering a camera*/
  24467. set: function (callback) {
  24468. if (this._onAfterCameraRenderObserver) {
  24469. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24470. }
  24471. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24472. },
  24473. enumerable: true,
  24474. configurable: true
  24475. });
  24476. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24477. /**
  24478. * Gets the gamepad manager associated with the scene
  24479. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24480. */
  24481. get: function () {
  24482. if (!this._gamepadManager) {
  24483. this._gamepadManager = new BABYLON.GamepadManager(this);
  24484. }
  24485. return this._gamepadManager;
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24491. /**
  24492. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24493. */
  24494. get: function () {
  24495. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24496. },
  24497. enumerable: true,
  24498. configurable: true
  24499. });
  24500. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24501. get: function () {
  24502. return this._useRightHandedSystem;
  24503. },
  24504. /**
  24505. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24506. */
  24507. set: function (value) {
  24508. if (this._useRightHandedSystem === value) {
  24509. return;
  24510. }
  24511. this._useRightHandedSystem = value;
  24512. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24513. },
  24514. enumerable: true,
  24515. configurable: true
  24516. });
  24517. /**
  24518. * Sets the step Id used by deterministic lock step
  24519. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24520. * @param newStepId defines the step Id
  24521. */
  24522. Scene.prototype.setStepId = function (newStepId) {
  24523. this._currentStepId = newStepId;
  24524. };
  24525. ;
  24526. /**
  24527. * Gets the step Id used by deterministic lock step
  24528. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24529. * @returns the step Id
  24530. */
  24531. Scene.prototype.getStepId = function () {
  24532. return this._currentStepId;
  24533. };
  24534. ;
  24535. /**
  24536. * Gets the internal step used by deterministic lock step
  24537. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24538. * @returns the internal step
  24539. */
  24540. Scene.prototype.getInternalStep = function () {
  24541. return this._currentInternalStep;
  24542. };
  24543. ;
  24544. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24545. get: function () {
  24546. return this._fogEnabled;
  24547. },
  24548. /**
  24549. * Gets or sets a boolean indicating if fog is enabled on this scene
  24550. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24551. */
  24552. set: function (value) {
  24553. if (this._fogEnabled === value) {
  24554. return;
  24555. }
  24556. this._fogEnabled = value;
  24557. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24558. },
  24559. enumerable: true,
  24560. configurable: true
  24561. });
  24562. Object.defineProperty(Scene.prototype, "fogMode", {
  24563. get: function () {
  24564. return this._fogMode;
  24565. },
  24566. /**
  24567. * Gets or sets the fog mode to use
  24568. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24569. */
  24570. set: function (value) {
  24571. if (this._fogMode === value) {
  24572. return;
  24573. }
  24574. this._fogMode = value;
  24575. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24576. },
  24577. enumerable: true,
  24578. configurable: true
  24579. });
  24580. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24581. get: function () {
  24582. return this._shadowsEnabled;
  24583. },
  24584. /**
  24585. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24586. */
  24587. set: function (value) {
  24588. if (this._shadowsEnabled === value) {
  24589. return;
  24590. }
  24591. this._shadowsEnabled = value;
  24592. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24593. },
  24594. enumerable: true,
  24595. configurable: true
  24596. });
  24597. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24598. get: function () {
  24599. return this._lightsEnabled;
  24600. },
  24601. /**
  24602. * Gets or sets a boolean indicating if lights are enabled on this scene
  24603. */
  24604. set: function (value) {
  24605. if (this._lightsEnabled === value) {
  24606. return;
  24607. }
  24608. this._lightsEnabled = value;
  24609. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24610. },
  24611. enumerable: true,
  24612. configurable: true
  24613. });
  24614. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24615. /** The default material used on meshes when no material is affected */
  24616. get: function () {
  24617. if (!this._defaultMaterial) {
  24618. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24619. }
  24620. return this._defaultMaterial;
  24621. },
  24622. /** The default material used on meshes when no material is affected */
  24623. set: function (value) {
  24624. this._defaultMaterial = value;
  24625. },
  24626. enumerable: true,
  24627. configurable: true
  24628. });
  24629. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24630. get: function () {
  24631. return this._texturesEnabled;
  24632. },
  24633. /**
  24634. * Gets or sets a boolean indicating if textures are enabled on this scene
  24635. */
  24636. set: function (value) {
  24637. if (this._texturesEnabled === value) {
  24638. return;
  24639. }
  24640. this._texturesEnabled = value;
  24641. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24642. },
  24643. enumerable: true,
  24644. configurable: true
  24645. });
  24646. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24647. get: function () {
  24648. return this._skeletonsEnabled;
  24649. },
  24650. /**
  24651. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24652. */
  24653. set: function (value) {
  24654. if (this._skeletonsEnabled === value) {
  24655. return;
  24656. }
  24657. this._skeletonsEnabled = value;
  24658. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24659. },
  24660. enumerable: true,
  24661. configurable: true
  24662. });
  24663. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24664. /**
  24665. * Gets the postprocess render pipeline manager
  24666. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24667. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24668. */
  24669. get: function () {
  24670. if (!this._postProcessRenderPipelineManager) {
  24671. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24672. }
  24673. return this._postProcessRenderPipelineManager;
  24674. },
  24675. enumerable: true,
  24676. configurable: true
  24677. });
  24678. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24679. /**
  24680. * Gets the main soundtrack associated with the scene
  24681. */
  24682. get: function () {
  24683. if (!this._mainSoundTrack) {
  24684. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24685. }
  24686. return this._mainSoundTrack;
  24687. },
  24688. enumerable: true,
  24689. configurable: true
  24690. });
  24691. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24692. /** @hidden */
  24693. get: function () {
  24694. return this._alternateRendering;
  24695. },
  24696. enumerable: true,
  24697. configurable: true
  24698. });
  24699. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24700. /**
  24701. * Gets the list of frustum planes (built from the active camera)
  24702. */
  24703. get: function () {
  24704. return this._frustumPlanes;
  24705. },
  24706. enumerable: true,
  24707. configurable: true
  24708. });
  24709. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24710. /**
  24711. * Gets the current geometry buffer associated to the scene.
  24712. */
  24713. get: function () {
  24714. return this._geometryBufferRenderer;
  24715. },
  24716. /**
  24717. * Sets the current geometry buffer for the scene.
  24718. */
  24719. set: function (geometryBufferRenderer) {
  24720. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24721. this._geometryBufferRenderer = geometryBufferRenderer;
  24722. }
  24723. },
  24724. enumerable: true,
  24725. configurable: true
  24726. });
  24727. Object.defineProperty(Scene.prototype, "debugLayer", {
  24728. /**
  24729. * Gets the debug layer (aka Inspector) associated with the scene
  24730. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24731. */
  24732. get: function () {
  24733. if (!this._debugLayer) {
  24734. this._debugLayer = new BABYLON.DebugLayer(this);
  24735. }
  24736. return this._debugLayer;
  24737. },
  24738. enumerable: true,
  24739. configurable: true
  24740. });
  24741. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24742. /**
  24743. * Gets a boolean indicating if collisions are processed on a web worker
  24744. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24745. */
  24746. get: function () {
  24747. return this._workerCollisions;
  24748. },
  24749. set: function (enabled) {
  24750. if (!BABYLON.CollisionCoordinatorLegacy) {
  24751. return;
  24752. }
  24753. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24754. this._workerCollisions = enabled;
  24755. if (this.collisionCoordinator) {
  24756. this.collisionCoordinator.destroy();
  24757. }
  24758. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24759. this.collisionCoordinator.init(this);
  24760. },
  24761. enumerable: true,
  24762. configurable: true
  24763. });
  24764. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24765. /**
  24766. * Gets the octree used to boost mesh selection (picking)
  24767. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24768. */
  24769. get: function () {
  24770. return this._selectionOctree;
  24771. },
  24772. enumerable: true,
  24773. configurable: true
  24774. });
  24775. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24776. /**
  24777. * Gets the mesh that is currently under the pointer
  24778. */
  24779. get: function () {
  24780. return this._pointerOverMesh;
  24781. },
  24782. enumerable: true,
  24783. configurable: true
  24784. });
  24785. Object.defineProperty(Scene.prototype, "pointerX", {
  24786. /**
  24787. * Gets the current on-screen X position of the pointer
  24788. */
  24789. get: function () {
  24790. return this._pointerX;
  24791. },
  24792. enumerable: true,
  24793. configurable: true
  24794. });
  24795. Object.defineProperty(Scene.prototype, "pointerY", {
  24796. /**
  24797. * Gets the current on-screen Y position of the pointer
  24798. */
  24799. get: function () {
  24800. return this._pointerY;
  24801. },
  24802. enumerable: true,
  24803. configurable: true
  24804. });
  24805. /**
  24806. * Gets the cached material (ie. the latest rendered one)
  24807. * @returns the cached material
  24808. */
  24809. Scene.prototype.getCachedMaterial = function () {
  24810. return this._cachedMaterial;
  24811. };
  24812. /**
  24813. * Gets the cached effect (ie. the latest rendered one)
  24814. * @returns the cached effect
  24815. */
  24816. Scene.prototype.getCachedEffect = function () {
  24817. return this._cachedEffect;
  24818. };
  24819. /**
  24820. * Gets the cached visibility state (ie. the latest rendered one)
  24821. * @returns the cached visibility state
  24822. */
  24823. Scene.prototype.getCachedVisibility = function () {
  24824. return this._cachedVisibility;
  24825. };
  24826. /**
  24827. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24828. * @param material defines the current material
  24829. * @param effect defines the current effect
  24830. * @param visibility defines the current visibility state
  24831. * @returns true if one parameter is not cached
  24832. */
  24833. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24834. if (visibility === void 0) { visibility = 1; }
  24835. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24836. };
  24837. /**
  24838. * Gets the bounding box renderer associated with the scene
  24839. * @returns a BoundingBoxRenderer
  24840. */
  24841. Scene.prototype.getBoundingBoxRenderer = function () {
  24842. if (!this._boundingBoxRenderer) {
  24843. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24844. }
  24845. return this._boundingBoxRenderer;
  24846. };
  24847. /**
  24848. * Gets the outline renderer associated with the scene
  24849. * @returns a OutlineRenderer
  24850. */
  24851. Scene.prototype.getOutlineRenderer = function () {
  24852. return this._outlineRenderer;
  24853. };
  24854. /**
  24855. * Gets the engine associated with the scene
  24856. * @returns an Engine
  24857. */
  24858. Scene.prototype.getEngine = function () {
  24859. return this._engine;
  24860. };
  24861. /**
  24862. * Gets the total number of vertices rendered per frame
  24863. * @returns the total number of vertices rendered per frame
  24864. */
  24865. Scene.prototype.getTotalVertices = function () {
  24866. return this._totalVertices.current;
  24867. };
  24868. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24869. /**
  24870. * Gets the performance counter for total vertices
  24871. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24872. */
  24873. get: function () {
  24874. return this._totalVertices;
  24875. },
  24876. enumerable: true,
  24877. configurable: true
  24878. });
  24879. /**
  24880. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24881. * @returns the total number of active indices rendered per frame
  24882. */
  24883. Scene.prototype.getActiveIndices = function () {
  24884. return this._activeIndices.current;
  24885. };
  24886. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24887. /**
  24888. * Gets the performance counter for active indices
  24889. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24890. */
  24891. get: function () {
  24892. return this._activeIndices;
  24893. },
  24894. enumerable: true,
  24895. configurable: true
  24896. });
  24897. /**
  24898. * Gets the total number of active particles rendered per frame
  24899. * @returns the total number of active particles rendered per frame
  24900. */
  24901. Scene.prototype.getActiveParticles = function () {
  24902. return this._activeParticles.current;
  24903. };
  24904. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24905. /**
  24906. * Gets the performance counter for active particles
  24907. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24908. */
  24909. get: function () {
  24910. return this._activeParticles;
  24911. },
  24912. enumerable: true,
  24913. configurable: true
  24914. });
  24915. /**
  24916. * Gets the total number of active bones rendered per frame
  24917. * @returns the total number of active bones rendered per frame
  24918. */
  24919. Scene.prototype.getActiveBones = function () {
  24920. return this._activeBones.current;
  24921. };
  24922. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24923. /**
  24924. * Gets the performance counter for active bones
  24925. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24926. */
  24927. get: function () {
  24928. return this._activeBones;
  24929. },
  24930. enumerable: true,
  24931. configurable: true
  24932. });
  24933. /** @hidden */
  24934. Scene.prototype.getInterFramePerfCounter = function () {
  24935. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24936. return 0;
  24937. };
  24938. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24939. /** @hidden */
  24940. get: function () {
  24941. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24942. return null;
  24943. },
  24944. enumerable: true,
  24945. configurable: true
  24946. });
  24947. /** @hidden */
  24948. Scene.prototype.getLastFrameDuration = function () {
  24949. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24950. return 0;
  24951. };
  24952. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24953. /** @hidden */
  24954. get: function () {
  24955. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24956. return null;
  24957. },
  24958. enumerable: true,
  24959. configurable: true
  24960. });
  24961. /** @hidden */
  24962. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24963. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24964. return 0;
  24965. };
  24966. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24967. /** @hidden */
  24968. get: function () {
  24969. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24970. return null;
  24971. },
  24972. enumerable: true,
  24973. configurable: true
  24974. });
  24975. /**
  24976. * Gets the array of active meshes
  24977. * @returns an array of AbstractMesh
  24978. */
  24979. Scene.prototype.getActiveMeshes = function () {
  24980. return this._activeMeshes;
  24981. };
  24982. /** @hidden */
  24983. Scene.prototype.getRenderTargetsDuration = function () {
  24984. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24985. return 0;
  24986. };
  24987. /** @hidden */
  24988. Scene.prototype.getRenderDuration = function () {
  24989. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24990. return 0;
  24991. };
  24992. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24993. /** @hidden */
  24994. get: function () {
  24995. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24996. return null;
  24997. },
  24998. enumerable: true,
  24999. configurable: true
  25000. });
  25001. /** @hidden */
  25002. Scene.prototype.getParticlesDuration = function () {
  25003. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25004. return 0;
  25005. };
  25006. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25007. /** @hidden */
  25008. get: function () {
  25009. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25010. return null;
  25011. },
  25012. enumerable: true,
  25013. configurable: true
  25014. });
  25015. /** @hidden */
  25016. Scene.prototype.getSpritesDuration = function () {
  25017. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25018. return 0;
  25019. };
  25020. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25021. /** @hidden */
  25022. get: function () {
  25023. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25024. return null;
  25025. },
  25026. enumerable: true,
  25027. configurable: true
  25028. });
  25029. /**
  25030. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25031. * @returns a number
  25032. */
  25033. Scene.prototype.getAnimationRatio = function () {
  25034. return this._animationRatio;
  25035. };
  25036. /**
  25037. * Gets an unique Id for the current frame
  25038. * @returns a number
  25039. */
  25040. Scene.prototype.getRenderId = function () {
  25041. return this._renderId;
  25042. };
  25043. /** Call this function if you want to manually increment the render Id*/
  25044. Scene.prototype.incrementRenderId = function () {
  25045. this._renderId++;
  25046. };
  25047. Scene.prototype._updatePointerPosition = function (evt) {
  25048. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25049. if (!canvasRect) {
  25050. return;
  25051. }
  25052. this._pointerX = evt.clientX - canvasRect.left;
  25053. this._pointerY = evt.clientY - canvasRect.top;
  25054. this._unTranslatedPointerX = this._pointerX;
  25055. this._unTranslatedPointerY = this._pointerY;
  25056. };
  25057. Scene.prototype._createUbo = function () {
  25058. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25059. this._sceneUbo.addUniform("viewProjection", 16);
  25060. this._sceneUbo.addUniform("view", 16);
  25061. };
  25062. Scene.prototype._createAlternateUbo = function () {
  25063. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25064. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25065. this._alternateSceneUbo.addUniform("view", 16);
  25066. };
  25067. // Pointers handling
  25068. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25069. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25070. if (result) {
  25071. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25072. }
  25073. return result;
  25074. };
  25075. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25076. if (pointerInfo.pickInfo) {
  25077. if (!pointerInfo.pickInfo.ray) {
  25078. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25079. }
  25080. }
  25081. };
  25082. /**
  25083. * Use this method to simulate a pointer move on a mesh
  25084. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25085. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25086. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25087. * @returns the current scene
  25088. */
  25089. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25090. var evt = new PointerEvent("pointermove", pointerEventInit);
  25091. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25092. return this;
  25093. }
  25094. return this._processPointerMove(pickResult, evt);
  25095. };
  25096. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25097. var canvas = this._engine.getRenderingCanvas();
  25098. if (!canvas) {
  25099. return this;
  25100. }
  25101. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25102. this.setPointerOverSprite(null);
  25103. this.setPointerOverMesh(pickResult.pickedMesh);
  25104. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25105. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25106. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25107. }
  25108. else {
  25109. canvas.style.cursor = this.hoverCursor;
  25110. }
  25111. }
  25112. else {
  25113. canvas.style.cursor = this.defaultCursor;
  25114. }
  25115. }
  25116. else {
  25117. this.setPointerOverMesh(null);
  25118. // Sprites
  25119. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25120. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25121. this.setPointerOverSprite(pickResult.pickedSprite);
  25122. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25123. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25124. }
  25125. else {
  25126. canvas.style.cursor = this.hoverCursor;
  25127. }
  25128. }
  25129. else {
  25130. this.setPointerOverSprite(null);
  25131. // Restore pointer
  25132. canvas.style.cursor = this.defaultCursor;
  25133. }
  25134. }
  25135. if (pickResult) {
  25136. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25137. if (this.onPointerMove) {
  25138. this.onPointerMove(evt, pickResult, type);
  25139. }
  25140. if (this.onPointerObservable.hasObservers()) {
  25141. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25142. this._setRayOnPointerInfo(pi);
  25143. this.onPointerObservable.notifyObservers(pi, type);
  25144. }
  25145. }
  25146. return this;
  25147. };
  25148. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25149. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25150. if (pickResult) {
  25151. pi.ray = pickResult.ray;
  25152. }
  25153. this.onPrePointerObservable.notifyObservers(pi, type);
  25154. if (pi.skipOnPointerObservable) {
  25155. return true;
  25156. }
  25157. else {
  25158. return false;
  25159. }
  25160. };
  25161. /**
  25162. * Use this method to simulate a pointer down on a mesh
  25163. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25164. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25165. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25166. * @returns the current scene
  25167. */
  25168. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25169. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25170. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25171. return this;
  25172. }
  25173. return this._processPointerDown(pickResult, evt);
  25174. };
  25175. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25176. var _this = this;
  25177. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25178. this._pickedDownMesh = pickResult.pickedMesh;
  25179. var actionManager = pickResult.pickedMesh.actionManager;
  25180. if (actionManager) {
  25181. if (actionManager.hasPickTriggers) {
  25182. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25183. switch (evt.button) {
  25184. case 0:
  25185. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25186. break;
  25187. case 1:
  25188. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25189. break;
  25190. case 2:
  25191. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25192. break;
  25193. }
  25194. }
  25195. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25196. window.setTimeout(function () {
  25197. 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);
  25198. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25199. if (_this._totalPointersPressed !== 0 &&
  25200. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25201. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25202. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25203. _this._startingPointerTime = 0;
  25204. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25205. }
  25206. }
  25207. }, Scene.LongPressDelay);
  25208. }
  25209. }
  25210. }
  25211. if (pickResult) {
  25212. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25213. if (this.onPointerDown) {
  25214. this.onPointerDown(evt, pickResult, type);
  25215. }
  25216. if (this.onPointerObservable.hasObservers()) {
  25217. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25218. this._setRayOnPointerInfo(pi);
  25219. this.onPointerObservable.notifyObservers(pi, type);
  25220. }
  25221. }
  25222. return this;
  25223. };
  25224. /**
  25225. * Use this method to simulate a pointer up on a mesh
  25226. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25227. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25228. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25229. * @returns the current scene
  25230. */
  25231. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25232. var evt = new PointerEvent("pointerup", pointerEventInit);
  25233. var clickInfo = new ClickInfo();
  25234. clickInfo.singleClick = true;
  25235. clickInfo.ignore = true;
  25236. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25237. return this;
  25238. }
  25239. return this._processPointerUp(pickResult, evt, clickInfo);
  25240. };
  25241. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25242. if (pickResult && pickResult && pickResult.pickedMesh) {
  25243. this._pickedUpMesh = pickResult.pickedMesh;
  25244. if (this._pickedDownMesh === this._pickedUpMesh) {
  25245. if (this.onPointerPick) {
  25246. this.onPointerPick(evt, pickResult);
  25247. }
  25248. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25249. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25250. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25251. this._setRayOnPointerInfo(pi);
  25252. this.onPointerObservable.notifyObservers(pi, type_1);
  25253. }
  25254. }
  25255. if (pickResult.pickedMesh.actionManager) {
  25256. if (clickInfo.ignore) {
  25257. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25258. }
  25259. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25260. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25261. }
  25262. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25263. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25264. }
  25265. }
  25266. }
  25267. if (this._pickedDownMesh &&
  25268. this._pickedDownMesh.actionManager &&
  25269. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25270. this._pickedDownMesh !== this._pickedUpMesh) {
  25271. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25272. }
  25273. var type = BABYLON.PointerEventTypes.POINTERUP;
  25274. if (this.onPointerObservable.hasObservers()) {
  25275. if (!clickInfo.ignore) {
  25276. if (!clickInfo.hasSwiped) {
  25277. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25278. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25279. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25280. this._setRayOnPointerInfo(pi);
  25281. this.onPointerObservable.notifyObservers(pi, type_2);
  25282. }
  25283. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25284. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25285. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25286. this._setRayOnPointerInfo(pi);
  25287. this.onPointerObservable.notifyObservers(pi, type_3);
  25288. }
  25289. }
  25290. }
  25291. else {
  25292. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25293. this._setRayOnPointerInfo(pi);
  25294. this.onPointerObservable.notifyObservers(pi, type);
  25295. }
  25296. }
  25297. if (this.onPointerUp) {
  25298. this.onPointerUp(evt, pickResult, type);
  25299. }
  25300. return this;
  25301. };
  25302. /**
  25303. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25304. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25305. * @returns true if the pointer was captured
  25306. */
  25307. Scene.prototype.isPointerCaptured = function (pointerId) {
  25308. if (pointerId === void 0) { pointerId = 0; }
  25309. return this._pointerCaptures[pointerId];
  25310. };
  25311. /**
  25312. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25313. * @param attachUp defines if you want to attach events to pointerup
  25314. * @param attachDown defines if you want to attach events to pointerdown
  25315. * @param attachMove defines if you want to attach events to pointermove
  25316. */
  25317. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25318. var _this = this;
  25319. if (attachUp === void 0) { attachUp = true; }
  25320. if (attachDown === void 0) { attachDown = true; }
  25321. if (attachMove === void 0) { attachMove = true; }
  25322. this._initActionManager = function (act, clickInfo) {
  25323. if (!_this._meshPickProceed) {
  25324. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25325. _this._currentPickResult = pickResult;
  25326. if (pickResult) {
  25327. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25328. }
  25329. _this._meshPickProceed = true;
  25330. }
  25331. return act;
  25332. };
  25333. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25334. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25335. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25336. btn !== _this._previousButtonPressed) {
  25337. _this._doubleClickOccured = false;
  25338. clickInfo.singleClick = true;
  25339. clickInfo.ignore = false;
  25340. cb(clickInfo, _this._currentPickResult);
  25341. }
  25342. };
  25343. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25344. var clickInfo = new ClickInfo();
  25345. _this._currentPickResult = null;
  25346. var act = null;
  25347. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25348. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25349. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25350. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25351. act = _this._initActionManager(act, clickInfo);
  25352. if (act)
  25353. checkPicking = act.hasPickTriggers;
  25354. }
  25355. if (checkPicking) {
  25356. var btn = evt.button;
  25357. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25358. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25359. if (!clickInfo.hasSwiped) {
  25360. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25361. if (!checkSingleClickImmediately) {
  25362. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25363. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25364. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25365. act = _this._initActionManager(act, clickInfo);
  25366. if (act)
  25367. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25368. }
  25369. }
  25370. if (checkSingleClickImmediately) {
  25371. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25372. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25373. btn !== _this._previousButtonPressed) {
  25374. clickInfo.singleClick = true;
  25375. cb(clickInfo, _this._currentPickResult);
  25376. }
  25377. }
  25378. // at least one double click is required to be check and exclusive double click is enabled
  25379. else {
  25380. // wait that no double click has been raised during the double click delay
  25381. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25382. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25383. }
  25384. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25385. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25386. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25387. act = _this._initActionManager(act, clickInfo);
  25388. if (act)
  25389. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25390. }
  25391. if (checkDoubleClick) {
  25392. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25393. if (btn === _this._previousButtonPressed &&
  25394. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25395. !_this._doubleClickOccured) {
  25396. // pointer has not moved for 2 clicks, it's a double click
  25397. if (!clickInfo.hasSwiped &&
  25398. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25399. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25400. _this._previousStartingPointerTime = 0;
  25401. _this._doubleClickOccured = true;
  25402. clickInfo.doubleClick = true;
  25403. clickInfo.ignore = false;
  25404. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25405. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25406. }
  25407. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25408. cb(clickInfo, _this._currentPickResult);
  25409. }
  25410. // if the two successive clicks are too far, it's just two simple clicks
  25411. else {
  25412. _this._doubleClickOccured = false;
  25413. _this._previousStartingPointerTime = _this._startingPointerTime;
  25414. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25415. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25416. _this._previousButtonPressed = btn;
  25417. if (Scene.ExclusiveDoubleClickMode) {
  25418. if (_this._previousDelayedSimpleClickTimeout) {
  25419. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25420. }
  25421. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25422. cb(clickInfo, _this._previousPickResult);
  25423. }
  25424. else {
  25425. cb(clickInfo, _this._currentPickResult);
  25426. }
  25427. }
  25428. }
  25429. // just the first click of the double has been raised
  25430. else {
  25431. _this._doubleClickOccured = false;
  25432. _this._previousStartingPointerTime = _this._startingPointerTime;
  25433. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25434. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25435. _this._previousButtonPressed = btn;
  25436. }
  25437. }
  25438. }
  25439. }
  25440. clickInfo.ignore = true;
  25441. cb(clickInfo, _this._currentPickResult);
  25442. };
  25443. this._spritePredicate = function (sprite) {
  25444. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25445. };
  25446. this._onPointerMove = function (evt) {
  25447. _this._updatePointerPosition(evt);
  25448. // PreObservable support
  25449. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25450. return;
  25451. }
  25452. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25453. return;
  25454. }
  25455. if (!_this.pointerMovePredicate) {
  25456. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25457. }
  25458. // Meshes
  25459. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25460. _this._processPointerMove(pickResult, evt);
  25461. };
  25462. this._onPointerDown = function (evt) {
  25463. _this._totalPointersPressed++;
  25464. _this._pickedDownMesh = null;
  25465. _this._meshPickProceed = false;
  25466. _this._updatePointerPosition(evt);
  25467. if (_this.preventDefaultOnPointerDown && canvas) {
  25468. evt.preventDefault();
  25469. canvas.focus();
  25470. }
  25471. // PreObservable support
  25472. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25473. return;
  25474. }
  25475. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25476. return;
  25477. }
  25478. _this._pointerCaptures[evt.pointerId] = true;
  25479. _this._startingPointerPosition.x = _this._pointerX;
  25480. _this._startingPointerPosition.y = _this._pointerY;
  25481. _this._startingPointerTime = Date.now();
  25482. if (!_this.pointerDownPredicate) {
  25483. _this.pointerDownPredicate = function (mesh) {
  25484. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25485. };
  25486. }
  25487. // Meshes
  25488. _this._pickedDownMesh = null;
  25489. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25490. _this._processPointerDown(pickResult, evt);
  25491. // Sprites
  25492. _this._pickedDownSprite = null;
  25493. if (_this.spriteManagers.length > 0) {
  25494. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25495. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25496. if (pickResult.pickedSprite.actionManager) {
  25497. _this._pickedDownSprite = pickResult.pickedSprite;
  25498. switch (evt.button) {
  25499. case 0:
  25500. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25501. break;
  25502. case 1:
  25503. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25504. break;
  25505. case 2:
  25506. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25507. break;
  25508. }
  25509. if (pickResult.pickedSprite.actionManager) {
  25510. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25511. }
  25512. }
  25513. }
  25514. }
  25515. };
  25516. this._onPointerUp = function (evt) {
  25517. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25518. return; // So we need to test it the pointer down was pressed before.
  25519. }
  25520. _this._totalPointersPressed--;
  25521. _this._pickedUpMesh = null;
  25522. _this._meshPickProceed = false;
  25523. _this._updatePointerPosition(evt);
  25524. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25525. // PreObservable support
  25526. if (_this.onPrePointerObservable.hasObservers()) {
  25527. if (!clickInfo.ignore) {
  25528. if (!clickInfo.hasSwiped) {
  25529. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25530. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25531. return;
  25532. }
  25533. }
  25534. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25535. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25536. return;
  25537. }
  25538. }
  25539. }
  25540. }
  25541. else {
  25542. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25543. return;
  25544. }
  25545. }
  25546. }
  25547. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25548. return;
  25549. }
  25550. _this._pointerCaptures[evt.pointerId] = false;
  25551. if (!_this.pointerUpPredicate) {
  25552. _this.pointerUpPredicate = function (mesh) {
  25553. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25554. };
  25555. }
  25556. // Meshes
  25557. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25558. _this._initActionManager(null, clickInfo);
  25559. }
  25560. if (!pickResult) {
  25561. pickResult = _this._currentPickResult;
  25562. }
  25563. _this._processPointerUp(pickResult, evt, clickInfo);
  25564. // Sprites
  25565. if (!clickInfo.ignore) {
  25566. if (_this.spriteManagers.length > 0) {
  25567. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25568. if (spritePickResult) {
  25569. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25570. if (spritePickResult.pickedSprite.actionManager) {
  25571. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25572. if (spritePickResult.pickedSprite.actionManager) {
  25573. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25574. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25575. }
  25576. }
  25577. }
  25578. }
  25579. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25580. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25581. }
  25582. }
  25583. }
  25584. }
  25585. _this._previousPickResult = _this._currentPickResult;
  25586. });
  25587. };
  25588. this._onKeyDown = function (evt) {
  25589. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25590. if (_this.onPreKeyboardObservable.hasObservers()) {
  25591. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25592. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25593. if (pi.skipOnPointerObservable) {
  25594. return;
  25595. }
  25596. }
  25597. if (_this.onKeyboardObservable.hasObservers()) {
  25598. var pi = new BABYLON.KeyboardInfo(type, evt);
  25599. _this.onKeyboardObservable.notifyObservers(pi, type);
  25600. }
  25601. if (_this.actionManager) {
  25602. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25603. }
  25604. };
  25605. this._onKeyUp = function (evt) {
  25606. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25607. if (_this.onPreKeyboardObservable.hasObservers()) {
  25608. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25609. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25610. if (pi.skipOnPointerObservable) {
  25611. return;
  25612. }
  25613. }
  25614. if (_this.onKeyboardObservable.hasObservers()) {
  25615. var pi = new BABYLON.KeyboardInfo(type, evt);
  25616. _this.onKeyboardObservable.notifyObservers(pi, type);
  25617. }
  25618. if (_this.actionManager) {
  25619. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25620. }
  25621. };
  25622. var engine = this.getEngine();
  25623. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25624. if (!canvas) {
  25625. return;
  25626. }
  25627. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25628. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25629. });
  25630. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25631. if (!canvas) {
  25632. return;
  25633. }
  25634. canvas.removeEventListener("keydown", _this._onKeyDown);
  25635. canvas.removeEventListener("keyup", _this._onKeyUp);
  25636. });
  25637. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25638. var canvas = this._engine.getRenderingCanvas();
  25639. if (!canvas) {
  25640. return;
  25641. }
  25642. if (attachMove) {
  25643. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25644. // Wheel
  25645. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25646. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25647. }
  25648. if (attachDown) {
  25649. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25650. }
  25651. if (attachUp) {
  25652. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25653. }
  25654. canvas.tabIndex = 1;
  25655. };
  25656. /** Detaches all event handlers*/
  25657. Scene.prototype.detachControl = function () {
  25658. var engine = this.getEngine();
  25659. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25660. var canvas = engine.getRenderingCanvas();
  25661. if (!canvas) {
  25662. return;
  25663. }
  25664. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25665. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25666. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25667. if (this._onCanvasBlurObserver) {
  25668. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25669. }
  25670. if (this._onCanvasFocusObserver) {
  25671. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25672. }
  25673. // Wheel
  25674. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25675. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25676. // Keyboard
  25677. canvas.removeEventListener("keydown", this._onKeyDown);
  25678. canvas.removeEventListener("keyup", this._onKeyUp);
  25679. // Observables
  25680. this.onKeyboardObservable.clear();
  25681. this.onPreKeyboardObservable.clear();
  25682. this.onPointerObservable.clear();
  25683. this.onPrePointerObservable.clear();
  25684. };
  25685. /**
  25686. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25687. * Delay loaded resources are not taking in account
  25688. * @return true if all required resources are ready
  25689. */
  25690. Scene.prototype.isReady = function () {
  25691. if (this._isDisposed) {
  25692. return false;
  25693. }
  25694. if (this._pendingData.length > 0) {
  25695. return false;
  25696. }
  25697. var index;
  25698. var engine = this.getEngine();
  25699. // Geometries
  25700. for (index = 0; index < this._geometries.length; index++) {
  25701. var geometry = this._geometries[index];
  25702. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25703. return false;
  25704. }
  25705. }
  25706. // Meshes
  25707. for (index = 0; index < this.meshes.length; index++) {
  25708. var mesh = this.meshes[index];
  25709. if (!mesh.isEnabled()) {
  25710. continue;
  25711. }
  25712. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25713. continue;
  25714. }
  25715. if (!mesh.isReady(true)) {
  25716. return false;
  25717. }
  25718. // Effect layers
  25719. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25720. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25721. var layer = _a[_i];
  25722. if (!layer.hasMesh(mesh)) {
  25723. continue;
  25724. }
  25725. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25726. var subMesh = _c[_b];
  25727. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25728. return false;
  25729. }
  25730. }
  25731. }
  25732. }
  25733. // Post-processes
  25734. if (this.activeCameras && this.activeCameras.length > 0) {
  25735. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25736. var camera = _e[_d];
  25737. if (!camera.isReady(true)) {
  25738. return false;
  25739. }
  25740. }
  25741. }
  25742. else if (this.activeCamera) {
  25743. if (!this.activeCamera.isReady(true)) {
  25744. return false;
  25745. }
  25746. }
  25747. // Particles
  25748. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25749. var particleSystem = _g[_f];
  25750. if (!particleSystem.isReady()) {
  25751. return false;
  25752. }
  25753. }
  25754. return true;
  25755. };
  25756. /** Resets all cached information relative to material (including effect and visibility) */
  25757. Scene.prototype.resetCachedMaterial = function () {
  25758. this._cachedMaterial = null;
  25759. this._cachedEffect = null;
  25760. this._cachedVisibility = null;
  25761. };
  25762. /**
  25763. * Registers a function to be called before every frame render
  25764. * @param func defines the function to register
  25765. */
  25766. Scene.prototype.registerBeforeRender = function (func) {
  25767. this.onBeforeRenderObservable.add(func);
  25768. };
  25769. /**
  25770. * Unregisters a function called before every frame render
  25771. * @param func defines the function to unregister
  25772. */
  25773. Scene.prototype.unregisterBeforeRender = function (func) {
  25774. this.onBeforeRenderObservable.removeCallback(func);
  25775. };
  25776. /**
  25777. * Registers a function to be called after every frame render
  25778. * @param func defines the function to register
  25779. */
  25780. Scene.prototype.registerAfterRender = function (func) {
  25781. this.onAfterRenderObservable.add(func);
  25782. };
  25783. /**
  25784. * Unregisters a function called after every frame render
  25785. * @param func defines the function to unregister
  25786. */
  25787. Scene.prototype.unregisterAfterRender = function (func) {
  25788. this.onAfterRenderObservable.removeCallback(func);
  25789. };
  25790. Scene.prototype._executeOnceBeforeRender = function (func) {
  25791. var _this = this;
  25792. var execFunc = function () {
  25793. func();
  25794. setTimeout(function () {
  25795. _this.unregisterBeforeRender(execFunc);
  25796. });
  25797. };
  25798. this.registerBeforeRender(execFunc);
  25799. };
  25800. /**
  25801. * The provided function will run before render once and will be disposed afterwards.
  25802. * A timeout delay can be provided so that the function will be executed in N ms.
  25803. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25804. * @param func The function to be executed.
  25805. * @param timeout optional delay in ms
  25806. */
  25807. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25808. var _this = this;
  25809. if (timeout !== undefined) {
  25810. setTimeout(function () {
  25811. _this._executeOnceBeforeRender(func);
  25812. }, timeout);
  25813. }
  25814. else {
  25815. this._executeOnceBeforeRender(func);
  25816. }
  25817. };
  25818. /** @hidden */
  25819. Scene.prototype._addPendingData = function (data) {
  25820. this._pendingData.push(data);
  25821. };
  25822. /** @hidden */
  25823. Scene.prototype._removePendingData = function (data) {
  25824. var wasLoading = this.isLoading;
  25825. var index = this._pendingData.indexOf(data);
  25826. if (index !== -1) {
  25827. this._pendingData.splice(index, 1);
  25828. }
  25829. if (wasLoading && !this.isLoading) {
  25830. this.onDataLoadedObservable.notifyObservers(this);
  25831. }
  25832. };
  25833. /**
  25834. * Returns the number of items waiting to be loaded
  25835. * @returns the number of items waiting to be loaded
  25836. */
  25837. Scene.prototype.getWaitingItemsCount = function () {
  25838. return this._pendingData.length;
  25839. };
  25840. Object.defineProperty(Scene.prototype, "isLoading", {
  25841. /**
  25842. * Returns a boolean indicating if the scene is still loading data
  25843. */
  25844. get: function () {
  25845. return this._pendingData.length > 0;
  25846. },
  25847. enumerable: true,
  25848. configurable: true
  25849. });
  25850. /**
  25851. * Registers a function to be executed when the scene is ready
  25852. * @param {Function} func - the function to be executed
  25853. */
  25854. Scene.prototype.executeWhenReady = function (func) {
  25855. var _this = this;
  25856. this.onReadyObservable.add(func);
  25857. if (this._executeWhenReadyTimeoutId !== -1) {
  25858. return;
  25859. }
  25860. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25861. _this._checkIsReady();
  25862. }, 150);
  25863. };
  25864. /**
  25865. * Returns a promise that resolves when the scene is ready
  25866. * @returns A promise that resolves when the scene is ready
  25867. */
  25868. Scene.prototype.whenReadyAsync = function () {
  25869. var _this = this;
  25870. return new Promise(function (resolve) {
  25871. _this.executeWhenReady(function () {
  25872. resolve();
  25873. });
  25874. });
  25875. };
  25876. /** @hidden */
  25877. Scene.prototype._checkIsReady = function () {
  25878. var _this = this;
  25879. if (this.isReady()) {
  25880. this.onReadyObservable.notifyObservers(this);
  25881. this.onReadyObservable.clear();
  25882. this._executeWhenReadyTimeoutId = -1;
  25883. return;
  25884. }
  25885. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25886. _this._checkIsReady();
  25887. }, 150);
  25888. };
  25889. // Animations
  25890. /**
  25891. * Will start the animation sequence of a given target
  25892. * @param target defines the target
  25893. * @param from defines from which frame should animation start
  25894. * @param to defines until which frame should animation run.
  25895. * @param weight defines the weight to apply to the animation (1.0 by default)
  25896. * @param loop defines if the animation loops
  25897. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25898. * @param onAnimationEnd defines the function to be executed when the animation ends
  25899. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25900. * @returns the animatable object created for this animation
  25901. */
  25902. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25903. if (weight === void 0) { weight = 1.0; }
  25904. if (speedRatio === void 0) { speedRatio = 1.0; }
  25905. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25906. returnedAnimatable.weight = weight;
  25907. return returnedAnimatable;
  25908. };
  25909. /**
  25910. * Will start the animation sequence of a given target
  25911. * @param target defines the target
  25912. * @param from defines from which frame should animation start
  25913. * @param to defines until which frame should animation run.
  25914. * @param loop defines if the animation loops
  25915. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25916. * @param onAnimationEnd defines the function to be executed when the animation ends
  25917. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25918. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25919. * @returns the animatable object created for this animation
  25920. */
  25921. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25922. if (speedRatio === void 0) { speedRatio = 1.0; }
  25923. if (stopCurrent === void 0) { stopCurrent = true; }
  25924. if (from > to && speedRatio > 0) {
  25925. speedRatio *= -1;
  25926. }
  25927. if (stopCurrent) {
  25928. this.stopAnimation(target);
  25929. }
  25930. if (!animatable) {
  25931. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25932. }
  25933. // Local animations
  25934. if (target.animations) {
  25935. animatable.appendAnimations(target, target.animations);
  25936. }
  25937. // Children animations
  25938. if (target.getAnimatables) {
  25939. var animatables = target.getAnimatables();
  25940. for (var index = 0; index < animatables.length; index++) {
  25941. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25942. }
  25943. }
  25944. animatable.reset();
  25945. return animatable;
  25946. };
  25947. /**
  25948. * Begin a new animation on a given node
  25949. * @param target defines the target where the animation will take place
  25950. * @param animations defines the list of animations to start
  25951. * @param from defines the initial value
  25952. * @param to defines the final value
  25953. * @param loop defines if you want animation to loop (off by default)
  25954. * @param speedRatio defines the speed ratio to apply to all animations
  25955. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25956. * @returns the list of created animatables
  25957. */
  25958. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25959. if (speedRatio === undefined) {
  25960. speedRatio = 1.0;
  25961. }
  25962. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25963. return animatable;
  25964. };
  25965. /**
  25966. * Begin a new animation on a given node and its hierarchy
  25967. * @param target defines the root node where the animation will take place
  25968. * @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.
  25969. * @param animations defines the list of animations to start
  25970. * @param from defines the initial value
  25971. * @param to defines the final value
  25972. * @param loop defines if you want animation to loop (off by default)
  25973. * @param speedRatio defines the speed ratio to apply to all animations
  25974. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25975. * @returns the list of animatables created for all nodes
  25976. */
  25977. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25978. var children = target.getDescendants(directDescendantsOnly);
  25979. var result = [];
  25980. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25981. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25982. var child = children_1[_i];
  25983. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25984. }
  25985. return result;
  25986. };
  25987. /**
  25988. * Gets the animatable associated with a specific target
  25989. * @param target defines the target of the animatable
  25990. * @returns the required animatable if found
  25991. */
  25992. Scene.prototype.getAnimatableByTarget = function (target) {
  25993. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25994. if (this._activeAnimatables[index].target === target) {
  25995. return this._activeAnimatables[index];
  25996. }
  25997. }
  25998. return null;
  25999. };
  26000. /**
  26001. * Gets all animatables associated with a given target
  26002. * @param target defines the target to look animatables for
  26003. * @returns an array of Animatables
  26004. */
  26005. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26006. var result = [];
  26007. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26008. if (this._activeAnimatables[index].target === target) {
  26009. result.push(this._activeAnimatables[index]);
  26010. }
  26011. }
  26012. return result;
  26013. };
  26014. Object.defineProperty(Scene.prototype, "animatables", {
  26015. /**
  26016. * Gets all animatable attached to the scene
  26017. */
  26018. get: function () {
  26019. return this._activeAnimatables;
  26020. },
  26021. enumerable: true,
  26022. configurable: true
  26023. });
  26024. /**
  26025. * Will stop the animation of the given target
  26026. * @param target - the target
  26027. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26028. */
  26029. Scene.prototype.stopAnimation = function (target, animationName) {
  26030. var animatables = this.getAllAnimatablesByTarget(target);
  26031. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26032. var animatable = animatables_1[_i];
  26033. animatable.stop(animationName);
  26034. }
  26035. };
  26036. /**
  26037. * Stops and removes all animations that have been applied to the scene
  26038. */
  26039. Scene.prototype.stopAllAnimations = function () {
  26040. if (this._activeAnimatables) {
  26041. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26042. this._activeAnimatables[i].stop();
  26043. }
  26044. this._activeAnimatables = [];
  26045. }
  26046. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26047. var group = _a[_i];
  26048. group.stop();
  26049. }
  26050. };
  26051. Scene.prototype._animate = function () {
  26052. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26053. return;
  26054. }
  26055. // Getting time
  26056. var now = BABYLON.Tools.Now;
  26057. if (!this._animationTimeLast) {
  26058. if (this._pendingData.length > 0) {
  26059. return;
  26060. }
  26061. this._animationTimeLast = now;
  26062. }
  26063. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26064. this._animationTime += deltaTime;
  26065. this._animationTimeLast = now;
  26066. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26067. this._activeAnimatables[index]._animate(this._animationTime);
  26068. }
  26069. // Late animation bindings
  26070. this._processLateAnimationBindings();
  26071. };
  26072. /** @hidden */
  26073. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26074. var target = runtimeAnimation.target;
  26075. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26076. if (!target._lateAnimationHolders) {
  26077. target._lateAnimationHolders = {};
  26078. }
  26079. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26080. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26081. totalWeight: 0,
  26082. animations: [],
  26083. originalValue: originalValue
  26084. };
  26085. }
  26086. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26087. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26088. };
  26089. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26090. var normalizer = 1.0;
  26091. var finalPosition = BABYLON.Tmp.Vector3[0];
  26092. var finalScaling = BABYLON.Tmp.Vector3[1];
  26093. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26094. var startIndex = 0;
  26095. var originalAnimation = holder.animations[0];
  26096. var originalValue = holder.originalValue;
  26097. var scale = 1;
  26098. if (holder.totalWeight < 1.0) {
  26099. // We need to mix the original value in
  26100. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26101. scale = 1.0 - holder.totalWeight;
  26102. }
  26103. else {
  26104. startIndex = 1;
  26105. // We need to normalize the weights
  26106. normalizer = holder.totalWeight;
  26107. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26108. scale = originalAnimation.weight / normalizer;
  26109. if (scale == 1) {
  26110. return originalAnimation.currentValue;
  26111. }
  26112. }
  26113. finalScaling.scaleInPlace(scale);
  26114. finalPosition.scaleInPlace(scale);
  26115. finalQuaternion.scaleInPlace(scale);
  26116. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26117. var runtimeAnimation = holder.animations[animIndex];
  26118. var scale = runtimeAnimation.weight / normalizer;
  26119. var currentPosition = BABYLON.Tmp.Vector3[2];
  26120. var currentScaling = BABYLON.Tmp.Vector3[3];
  26121. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26122. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26123. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26124. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26125. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26126. }
  26127. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26128. return originalAnimation._workValue;
  26129. };
  26130. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26131. var originalAnimation = holder.animations[0];
  26132. var originalValue = holder.originalValue;
  26133. if (holder.animations.length === 1) {
  26134. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26135. }
  26136. var normalizer = 1.0;
  26137. var quaternions;
  26138. var weights;
  26139. if (holder.totalWeight < 1.0) {
  26140. var scale = 1.0 - holder.totalWeight;
  26141. quaternions = [];
  26142. weights = [];
  26143. quaternions.push(originalValue);
  26144. weights.push(scale);
  26145. }
  26146. else {
  26147. if (holder.animations.length === 2) { // Slerp as soon as we can
  26148. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26149. }
  26150. quaternions = [];
  26151. weights = [];
  26152. normalizer = holder.totalWeight;
  26153. }
  26154. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26155. var runtimeAnimation = holder.animations[animIndex];
  26156. quaternions.push(runtimeAnimation.currentValue);
  26157. weights.push(runtimeAnimation.weight / normalizer);
  26158. }
  26159. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26160. var cumulativeAmount = 0;
  26161. var cumulativeQuaternion = null;
  26162. for (var index = 0; index < quaternions.length;) {
  26163. if (!cumulativeQuaternion) {
  26164. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26165. cumulativeAmount = weights[index] + weights[index + 1];
  26166. index += 2;
  26167. continue;
  26168. }
  26169. cumulativeAmount += weights[index];
  26170. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26171. index++;
  26172. }
  26173. return cumulativeQuaternion;
  26174. };
  26175. Scene.prototype._processLateAnimationBindings = function () {
  26176. if (!this._registeredForLateAnimationBindings.length) {
  26177. return;
  26178. }
  26179. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26180. var target = this._registeredForLateAnimationBindings.data[index];
  26181. for (var path in target._lateAnimationHolders) {
  26182. var holder = target._lateAnimationHolders[path];
  26183. var originalAnimation = holder.animations[0];
  26184. var originalValue = holder.originalValue;
  26185. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26186. var finalValue = void 0;
  26187. if (matrixDecomposeMode) {
  26188. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26189. }
  26190. else {
  26191. var quaternionMode = originalValue.w !== undefined;
  26192. if (quaternionMode) {
  26193. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26194. }
  26195. else {
  26196. var startIndex = 0;
  26197. var normalizer = 1.0;
  26198. if (holder.totalWeight < 1.0) {
  26199. // We need to mix the original value in
  26200. if (originalValue.scale) {
  26201. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26202. }
  26203. else {
  26204. finalValue = originalValue * (1.0 - holder.totalWeight);
  26205. }
  26206. }
  26207. else {
  26208. // We need to normalize the weights
  26209. normalizer = holder.totalWeight;
  26210. var scale_1 = originalAnimation.weight / normalizer;
  26211. if (scale_1 !== 1) {
  26212. if (originalAnimation.currentValue.scale) {
  26213. finalValue = originalAnimation.currentValue.scale(scale_1);
  26214. }
  26215. else {
  26216. finalValue = originalAnimation.currentValue * scale_1;
  26217. }
  26218. }
  26219. else {
  26220. finalValue = originalAnimation.currentValue;
  26221. }
  26222. startIndex = 1;
  26223. }
  26224. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26225. var runtimeAnimation = holder.animations[animIndex];
  26226. var scale = runtimeAnimation.weight / normalizer;
  26227. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26228. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26229. }
  26230. else {
  26231. finalValue += runtimeAnimation.currentValue * scale;
  26232. }
  26233. }
  26234. }
  26235. }
  26236. target[path] = finalValue;
  26237. }
  26238. target._lateAnimationHolders = {};
  26239. }
  26240. this._registeredForLateAnimationBindings.reset();
  26241. };
  26242. // Matrix
  26243. /** @hidden */
  26244. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26245. this._useAlternateCameraConfiguration = active;
  26246. };
  26247. /**
  26248. * Gets the current view matrix
  26249. * @returns a Matrix
  26250. */
  26251. Scene.prototype.getViewMatrix = function () {
  26252. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26253. };
  26254. /**
  26255. * Gets the current projection matrix
  26256. * @returns a Matrix
  26257. */
  26258. Scene.prototype.getProjectionMatrix = function () {
  26259. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26260. };
  26261. /**
  26262. * Gets the current transform matrix
  26263. * @returns a Matrix made of View * Projection
  26264. */
  26265. Scene.prototype.getTransformMatrix = function () {
  26266. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26267. };
  26268. /**
  26269. * Sets the current transform matrix
  26270. * @param view defines the View matrix to use
  26271. * @param projection defines the Projection matrix to use
  26272. */
  26273. Scene.prototype.setTransformMatrix = function (view, projection) {
  26274. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26275. return;
  26276. }
  26277. this._viewUpdateFlag = view.updateFlag;
  26278. this._projectionUpdateFlag = projection.updateFlag;
  26279. this._viewMatrix = view;
  26280. this._projectionMatrix = projection;
  26281. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26282. // Update frustum
  26283. if (!this._frustumPlanes) {
  26284. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26285. }
  26286. else {
  26287. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26288. }
  26289. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26290. var otherCamera = this.activeCamera._alternateCamera;
  26291. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26292. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26293. }
  26294. if (this._sceneUbo.useUbo) {
  26295. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26296. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26297. this._sceneUbo.update();
  26298. }
  26299. };
  26300. /** @hidden */
  26301. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26302. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26303. return;
  26304. }
  26305. this._alternateViewUpdateFlag = view.updateFlag;
  26306. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26307. this._alternateViewMatrix = view;
  26308. this._alternateProjectionMatrix = projection;
  26309. if (!this._alternateTransformMatrix) {
  26310. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26311. }
  26312. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26313. if (!this._alternateSceneUbo) {
  26314. this._createAlternateUbo();
  26315. }
  26316. if (this._alternateSceneUbo.useUbo) {
  26317. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26318. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26319. this._alternateSceneUbo.update();
  26320. }
  26321. };
  26322. /**
  26323. * Gets the uniform buffer used to store scene data
  26324. * @returns a UniformBuffer
  26325. */
  26326. Scene.prototype.getSceneUniformBuffer = function () {
  26327. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26328. };
  26329. /**
  26330. * Gets an unique (relatively to the current scene) Id
  26331. * @returns an unique number for the scene
  26332. */
  26333. Scene.prototype.getUniqueId = function () {
  26334. var result = Scene._uniqueIdCounter;
  26335. Scene._uniqueIdCounter++;
  26336. return result;
  26337. };
  26338. /**
  26339. * Add a mesh to the list of scene's meshes
  26340. * @param newMesh defines the mesh to add
  26341. * @param recursive if all child meshes should also be added to the scene
  26342. */
  26343. Scene.prototype.addMesh = function (newMesh, recursive) {
  26344. var _this = this;
  26345. if (recursive === void 0) { recursive = false; }
  26346. this.meshes.push(newMesh);
  26347. //notify the collision coordinator
  26348. if (this.collisionCoordinator) {
  26349. this.collisionCoordinator.onMeshAdded(newMesh);
  26350. }
  26351. newMesh._resyncLightSources();
  26352. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26353. if (recursive) {
  26354. newMesh.getChildMeshes().forEach(function (m) {
  26355. _this.addMesh(m);
  26356. });
  26357. }
  26358. };
  26359. /**
  26360. * Remove a mesh for the list of scene's meshes
  26361. * @param toRemove defines the mesh to remove
  26362. * @param recursive if all child meshes should also be removed from the scene
  26363. * @returns the index where the mesh was in the mesh list
  26364. */
  26365. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26366. var _this = this;
  26367. if (recursive === void 0) { recursive = false; }
  26368. var index = this.meshes.indexOf(toRemove);
  26369. if (index !== -1) {
  26370. // Remove from the scene if mesh found
  26371. this.meshes.splice(index, 1);
  26372. }
  26373. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26374. if (recursive) {
  26375. toRemove.getChildMeshes().forEach(function (m) {
  26376. _this.removeMesh(m);
  26377. });
  26378. }
  26379. return index;
  26380. };
  26381. /**
  26382. * Add a transform node to the list of scene's transform nodes
  26383. * @param newTransformNode defines the transform node to add
  26384. */
  26385. Scene.prototype.addTransformNode = function (newTransformNode) {
  26386. this.transformNodes.push(newTransformNode);
  26387. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26388. };
  26389. /**
  26390. * Remove a transform node for the list of scene's transform nodes
  26391. * @param toRemove defines the transform node to remove
  26392. * @returns the index where the transform node was in the transform node list
  26393. */
  26394. Scene.prototype.removeTransformNode = function (toRemove) {
  26395. var index = this.transformNodes.indexOf(toRemove);
  26396. if (index !== -1) {
  26397. // Remove from the scene if found
  26398. this.transformNodes.splice(index, 1);
  26399. }
  26400. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26401. return index;
  26402. };
  26403. /**
  26404. * Remove a skeleton for the list of scene's skeletons
  26405. * @param toRemove defines the skeleton to remove
  26406. * @returns the index where the skeleton was in the skeleton list
  26407. */
  26408. Scene.prototype.removeSkeleton = function (toRemove) {
  26409. var index = this.skeletons.indexOf(toRemove);
  26410. if (index !== -1) {
  26411. // Remove from the scene if found
  26412. this.skeletons.splice(index, 1);
  26413. }
  26414. return index;
  26415. };
  26416. /**
  26417. * Remove a morph target for the list of scene's morph targets
  26418. * @param toRemove defines the morph target to remove
  26419. * @returns the index where the morph target was in the morph target list
  26420. */
  26421. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26422. var index = this.morphTargetManagers.indexOf(toRemove);
  26423. if (index !== -1) {
  26424. // Remove from the scene if found
  26425. this.morphTargetManagers.splice(index, 1);
  26426. }
  26427. return index;
  26428. };
  26429. /**
  26430. * Remove a light for the list of scene's lights
  26431. * @param toRemove defines the light to remove
  26432. * @returns the index where the light was in the light list
  26433. */
  26434. Scene.prototype.removeLight = function (toRemove) {
  26435. var index = this.lights.indexOf(toRemove);
  26436. if (index !== -1) {
  26437. // Remove from meshes
  26438. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26439. var mesh = _a[_i];
  26440. mesh._removeLightSource(toRemove);
  26441. }
  26442. // Remove from the scene if mesh found
  26443. this.lights.splice(index, 1);
  26444. this.sortLightsByPriority();
  26445. }
  26446. this.onLightRemovedObservable.notifyObservers(toRemove);
  26447. return index;
  26448. };
  26449. /**
  26450. * Remove a camera for the list of scene's cameras
  26451. * @param toRemove defines the camera to remove
  26452. * @returns the index where the camera was in the camera list
  26453. */
  26454. Scene.prototype.removeCamera = function (toRemove) {
  26455. var index = this.cameras.indexOf(toRemove);
  26456. if (index !== -1) {
  26457. // Remove from the scene if mesh found
  26458. this.cameras.splice(index, 1);
  26459. }
  26460. // Remove from activeCameras
  26461. var index2 = this.activeCameras.indexOf(toRemove);
  26462. if (index2 !== -1) {
  26463. // Remove from the scene if mesh found
  26464. this.activeCameras.splice(index2, 1);
  26465. }
  26466. // Reset the activeCamera
  26467. if (this.activeCamera === toRemove) {
  26468. if (this.cameras.length > 0) {
  26469. this.activeCamera = this.cameras[0];
  26470. }
  26471. else {
  26472. this.activeCamera = null;
  26473. }
  26474. }
  26475. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26476. return index;
  26477. };
  26478. /**
  26479. * Remove a particle system for the list of scene's particle systems
  26480. * @param toRemove defines the particle system to remove
  26481. * @returns the index where the particle system was in the particle system list
  26482. */
  26483. Scene.prototype.removeParticleSystem = function (toRemove) {
  26484. var index = this.particleSystems.indexOf(toRemove);
  26485. if (index !== -1) {
  26486. this.particleSystems.splice(index, 1);
  26487. }
  26488. return index;
  26489. };
  26490. /**
  26491. * Remove a animation for the list of scene's animations
  26492. * @param toRemove defines the animation to remove
  26493. * @returns the index where the animation was in the animation list
  26494. */
  26495. Scene.prototype.removeAnimation = function (toRemove) {
  26496. var index = this.animations.indexOf(toRemove);
  26497. if (index !== -1) {
  26498. this.animations.splice(index, 1);
  26499. }
  26500. return index;
  26501. };
  26502. /**
  26503. * Removes the given animation group from this scene.
  26504. * @param toRemove The animation group to remove
  26505. * @returns The index of the removed animation group
  26506. */
  26507. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26508. var index = this.animationGroups.indexOf(toRemove);
  26509. if (index !== -1) {
  26510. this.animationGroups.splice(index, 1);
  26511. }
  26512. return index;
  26513. };
  26514. /**
  26515. * Removes the given multi-material from this scene.
  26516. * @param toRemove The multi-material to remove
  26517. * @returns The index of the removed multi-material
  26518. */
  26519. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26520. var index = this.multiMaterials.indexOf(toRemove);
  26521. if (index !== -1) {
  26522. this.multiMaterials.splice(index, 1);
  26523. }
  26524. return index;
  26525. };
  26526. /**
  26527. * Removes the given material from this scene.
  26528. * @param toRemove The material to remove
  26529. * @returns The index of the removed material
  26530. */
  26531. Scene.prototype.removeMaterial = function (toRemove) {
  26532. var index = this.materials.indexOf(toRemove);
  26533. if (index !== -1) {
  26534. this.materials.splice(index, 1);
  26535. }
  26536. return index;
  26537. };
  26538. /**
  26539. * Removes the given lens flare system from this scene.
  26540. * @param toRemove The lens flare system to remove
  26541. * @returns The index of the removed lens flare system
  26542. */
  26543. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26544. var index = this.lensFlareSystems.indexOf(toRemove);
  26545. if (index !== -1) {
  26546. this.lensFlareSystems.splice(index, 1);
  26547. }
  26548. return index;
  26549. };
  26550. /**
  26551. * Removes the given action manager from this scene.
  26552. * @param toRemove The action manager to remove
  26553. * @returns The index of the removed action manager
  26554. */
  26555. Scene.prototype.removeActionManager = function (toRemove) {
  26556. var index = this._actionManagers.indexOf(toRemove);
  26557. if (index !== -1) {
  26558. this._actionManagers.splice(index, 1);
  26559. }
  26560. return index;
  26561. };
  26562. /**
  26563. * Removes the given effect layer from this scene.
  26564. * @param toRemove defines the effect layer to remove
  26565. * @returns the index of the removed effect layer
  26566. */
  26567. Scene.prototype.removeEffectLayer = function (toRemove) {
  26568. var index = this.effectLayers.indexOf(toRemove);
  26569. if (index !== -1) {
  26570. this.effectLayers.splice(index, 1);
  26571. }
  26572. return index;
  26573. };
  26574. /**
  26575. * Removes the given texture from this scene.
  26576. * @param toRemove The texture to remove
  26577. * @returns The index of the removed texture
  26578. */
  26579. Scene.prototype.removeTexture = function (toRemove) {
  26580. var index = this.textures.indexOf(toRemove);
  26581. if (index !== -1) {
  26582. this.textures.splice(index, 1);
  26583. }
  26584. return index;
  26585. };
  26586. /**
  26587. * Adds the given light to this scene
  26588. * @param newLight The light to add
  26589. */
  26590. Scene.prototype.addLight = function (newLight) {
  26591. this.lights.push(newLight);
  26592. this.sortLightsByPriority();
  26593. // Add light to all meshes (To support if the light is removed and then readded)
  26594. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26595. var mesh = _a[_i];
  26596. if (mesh._lightSources.indexOf(newLight) === -1) {
  26597. mesh._lightSources.push(newLight);
  26598. mesh._resyncLightSources();
  26599. }
  26600. }
  26601. this.onNewLightAddedObservable.notifyObservers(newLight);
  26602. };
  26603. /**
  26604. * Sorts the list list based on light priorities
  26605. */
  26606. Scene.prototype.sortLightsByPriority = function () {
  26607. if (this.requireLightSorting) {
  26608. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26609. }
  26610. };
  26611. /**
  26612. * Adds the given camera to this scene
  26613. * @param newCamera The camera to add
  26614. */
  26615. Scene.prototype.addCamera = function (newCamera) {
  26616. this.cameras.push(newCamera);
  26617. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26618. };
  26619. /**
  26620. * Adds the given skeleton to this scene
  26621. * @param newSkeleton The skeleton to add
  26622. */
  26623. Scene.prototype.addSkeleton = function (newSkeleton) {
  26624. this.skeletons.push(newSkeleton);
  26625. };
  26626. /**
  26627. * Adds the given particle system to this scene
  26628. * @param newParticleSystem The particle system to add
  26629. */
  26630. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26631. this.particleSystems.push(newParticleSystem);
  26632. };
  26633. /**
  26634. * Adds the given animation to this scene
  26635. * @param newAnimation The animation to add
  26636. */
  26637. Scene.prototype.addAnimation = function (newAnimation) {
  26638. this.animations.push(newAnimation);
  26639. };
  26640. /**
  26641. * Adds the given animation group to this scene.
  26642. * @param newAnimationGroup The animation group to add
  26643. */
  26644. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26645. this.animationGroups.push(newAnimationGroup);
  26646. };
  26647. /**
  26648. * Adds the given multi-material to this scene
  26649. * @param newMultiMaterial The multi-material to add
  26650. */
  26651. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26652. this.multiMaterials.push(newMultiMaterial);
  26653. };
  26654. /**
  26655. * Adds the given material to this scene
  26656. * @param newMaterial The material to add
  26657. */
  26658. Scene.prototype.addMaterial = function (newMaterial) {
  26659. this.materials.push(newMaterial);
  26660. };
  26661. /**
  26662. * Adds the given morph target to this scene
  26663. * @param newMorphTargetManager The morph target to add
  26664. */
  26665. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26666. this.morphTargetManagers.push(newMorphTargetManager);
  26667. };
  26668. /**
  26669. * Adds the given geometry to this scene
  26670. * @param newGeometry The geometry to add
  26671. */
  26672. Scene.prototype.addGeometry = function (newGeometry) {
  26673. this._geometries.push(newGeometry);
  26674. };
  26675. /**
  26676. * Adds the given lens flare system to this scene
  26677. * @param newLensFlareSystem The lens flare system to add
  26678. */
  26679. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26680. this.lensFlareSystems.push(newLensFlareSystem);
  26681. };
  26682. /**
  26683. * Adds the given effect layer to this scene
  26684. * @param newEffectLayer defines the effect layer to add
  26685. */
  26686. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26687. this.effectLayers.push(newEffectLayer);
  26688. };
  26689. /**
  26690. * Adds the given action manager to this scene
  26691. * @param newActionManager The action manager to add
  26692. */
  26693. Scene.prototype.addActionManager = function (newActionManager) {
  26694. this._actionManagers.push(newActionManager);
  26695. };
  26696. /**
  26697. * Adds the given texture to this scene.
  26698. * @param newTexture The texture to add
  26699. */
  26700. Scene.prototype.addTexture = function (newTexture) {
  26701. this.textures.push(newTexture);
  26702. };
  26703. /**
  26704. * Switch active camera
  26705. * @param newCamera defines the new active camera
  26706. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26707. */
  26708. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26709. if (attachControl === void 0) { attachControl = true; }
  26710. var canvas = this._engine.getRenderingCanvas();
  26711. if (!canvas) {
  26712. return;
  26713. }
  26714. if (this.activeCamera) {
  26715. this.activeCamera.detachControl(canvas);
  26716. }
  26717. this.activeCamera = newCamera;
  26718. if (attachControl) {
  26719. newCamera.attachControl(canvas);
  26720. }
  26721. };
  26722. /**
  26723. * sets the active camera of the scene using its ID
  26724. * @param id defines the camera's ID
  26725. * @return the new active camera or null if none found.
  26726. */
  26727. Scene.prototype.setActiveCameraByID = function (id) {
  26728. var camera = this.getCameraByID(id);
  26729. if (camera) {
  26730. this.activeCamera = camera;
  26731. return camera;
  26732. }
  26733. return null;
  26734. };
  26735. /**
  26736. * sets the active camera of the scene using its name
  26737. * @param name defines the camera's name
  26738. * @returns the new active camera or null if none found.
  26739. */
  26740. Scene.prototype.setActiveCameraByName = function (name) {
  26741. var camera = this.getCameraByName(name);
  26742. if (camera) {
  26743. this.activeCamera = camera;
  26744. return camera;
  26745. }
  26746. return null;
  26747. };
  26748. /**
  26749. * get an animation group using its name
  26750. * @param name defines the material's name
  26751. * @return the animation group or null if none found.
  26752. */
  26753. Scene.prototype.getAnimationGroupByName = function (name) {
  26754. for (var index = 0; index < this.animationGroups.length; index++) {
  26755. if (this.animationGroups[index].name === name) {
  26756. return this.animationGroups[index];
  26757. }
  26758. }
  26759. return null;
  26760. };
  26761. /**
  26762. * get a material using its id
  26763. * @param id defines the material's ID
  26764. * @return the material or null if none found.
  26765. */
  26766. Scene.prototype.getMaterialByID = function (id) {
  26767. for (var index = 0; index < this.materials.length; index++) {
  26768. if (this.materials[index].id === id) {
  26769. return this.materials[index];
  26770. }
  26771. }
  26772. return null;
  26773. };
  26774. /**
  26775. * Gets a material using its name
  26776. * @param name defines the material's name
  26777. * @return the material or null if none found.
  26778. */
  26779. Scene.prototype.getMaterialByName = function (name) {
  26780. for (var index = 0; index < this.materials.length; index++) {
  26781. if (this.materials[index].name === name) {
  26782. return this.materials[index];
  26783. }
  26784. }
  26785. return null;
  26786. };
  26787. /**
  26788. * Gets a lens flare system using its name
  26789. * @param name defines the name to look for
  26790. * @returns the lens flare system or null if not found
  26791. */
  26792. Scene.prototype.getLensFlareSystemByName = function (name) {
  26793. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26794. if (this.lensFlareSystems[index].name === name) {
  26795. return this.lensFlareSystems[index];
  26796. }
  26797. }
  26798. return null;
  26799. };
  26800. /**
  26801. * Gets a lens flare system using its id
  26802. * @param id defines the id to look for
  26803. * @returns the lens flare system or null if not found
  26804. */
  26805. Scene.prototype.getLensFlareSystemByID = function (id) {
  26806. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26807. if (this.lensFlareSystems[index].id === id) {
  26808. return this.lensFlareSystems[index];
  26809. }
  26810. }
  26811. return null;
  26812. };
  26813. /**
  26814. * Gets a camera using its id
  26815. * @param id defines the id to look for
  26816. * @returns the camera or null if not found
  26817. */
  26818. Scene.prototype.getCameraByID = function (id) {
  26819. for (var index = 0; index < this.cameras.length; index++) {
  26820. if (this.cameras[index].id === id) {
  26821. return this.cameras[index];
  26822. }
  26823. }
  26824. return null;
  26825. };
  26826. /**
  26827. * Gets a camera using its unique id
  26828. * @param uniqueId defines the unique id to look for
  26829. * @returns the camera or null if not found
  26830. */
  26831. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26832. for (var index = 0; index < this.cameras.length; index++) {
  26833. if (this.cameras[index].uniqueId === uniqueId) {
  26834. return this.cameras[index];
  26835. }
  26836. }
  26837. return null;
  26838. };
  26839. /**
  26840. * Gets a camera using its name
  26841. * @param name defines the camera's name
  26842. * @return the camera or null if none found.
  26843. */
  26844. Scene.prototype.getCameraByName = function (name) {
  26845. for (var index = 0; index < this.cameras.length; index++) {
  26846. if (this.cameras[index].name === name) {
  26847. return this.cameras[index];
  26848. }
  26849. }
  26850. return null;
  26851. };
  26852. /**
  26853. * Gets a bone using its id
  26854. * @param id defines the bone's id
  26855. * @return the bone or null if not found
  26856. */
  26857. Scene.prototype.getBoneByID = function (id) {
  26858. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26859. var skeleton = this.skeletons[skeletonIndex];
  26860. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26861. if (skeleton.bones[boneIndex].id === id) {
  26862. return skeleton.bones[boneIndex];
  26863. }
  26864. }
  26865. }
  26866. return null;
  26867. };
  26868. /**
  26869. * Gets a bone using its id
  26870. * @param name defines the bone's name
  26871. * @return the bone or null if not found
  26872. */
  26873. Scene.prototype.getBoneByName = function (name) {
  26874. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26875. var skeleton = this.skeletons[skeletonIndex];
  26876. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26877. if (skeleton.bones[boneIndex].name === name) {
  26878. return skeleton.bones[boneIndex];
  26879. }
  26880. }
  26881. }
  26882. return null;
  26883. };
  26884. /**
  26885. * Gets a light node using its name
  26886. * @param name defines the the light's name
  26887. * @return the light or null if none found.
  26888. */
  26889. Scene.prototype.getLightByName = function (name) {
  26890. for (var index = 0; index < this.lights.length; index++) {
  26891. if (this.lights[index].name === name) {
  26892. return this.lights[index];
  26893. }
  26894. }
  26895. return null;
  26896. };
  26897. /**
  26898. * Gets a light node using its id
  26899. * @param id defines the light's id
  26900. * @return the light or null if none found.
  26901. */
  26902. Scene.prototype.getLightByID = function (id) {
  26903. for (var index = 0; index < this.lights.length; index++) {
  26904. if (this.lights[index].id === id) {
  26905. return this.lights[index];
  26906. }
  26907. }
  26908. return null;
  26909. };
  26910. /**
  26911. * Gets a light node using its scene-generated unique ID
  26912. * @param uniqueId defines the light's unique id
  26913. * @return the light or null if none found.
  26914. */
  26915. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26916. for (var index = 0; index < this.lights.length; index++) {
  26917. if (this.lights[index].uniqueId === uniqueId) {
  26918. return this.lights[index];
  26919. }
  26920. }
  26921. return null;
  26922. };
  26923. /**
  26924. * Gets a particle system by id
  26925. * @param id defines the particle system id
  26926. * @return the corresponding system or null if none found
  26927. */
  26928. Scene.prototype.getParticleSystemByID = function (id) {
  26929. for (var index = 0; index < this.particleSystems.length; index++) {
  26930. if (this.particleSystems[index].id === id) {
  26931. return this.particleSystems[index];
  26932. }
  26933. }
  26934. return null;
  26935. };
  26936. /**
  26937. * Gets a geometry using its ID
  26938. * @param id defines the geometry's id
  26939. * @return the geometry or null if none found.
  26940. */
  26941. Scene.prototype.getGeometryByID = function (id) {
  26942. for (var index = 0; index < this._geometries.length; index++) {
  26943. if (this._geometries[index].id === id) {
  26944. return this._geometries[index];
  26945. }
  26946. }
  26947. return null;
  26948. };
  26949. /**
  26950. * Add a new geometry to this scene
  26951. * @param geometry defines the geometry to be added to the scene.
  26952. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26953. * @return a boolean defining if the geometry was added or not
  26954. */
  26955. Scene.prototype.pushGeometry = function (geometry, force) {
  26956. if (!force && this.getGeometryByID(geometry.id)) {
  26957. return false;
  26958. }
  26959. this._geometries.push(geometry);
  26960. //notify the collision coordinator
  26961. if (this.collisionCoordinator) {
  26962. this.collisionCoordinator.onGeometryAdded(geometry);
  26963. }
  26964. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26965. return true;
  26966. };
  26967. /**
  26968. * Removes an existing geometry
  26969. * @param geometry defines the geometry to be removed from the scene
  26970. * @return a boolean defining if the geometry was removed or not
  26971. */
  26972. Scene.prototype.removeGeometry = function (geometry) {
  26973. var index = this._geometries.indexOf(geometry);
  26974. if (index > -1) {
  26975. this._geometries.splice(index, 1);
  26976. //notify the collision coordinator
  26977. if (this.collisionCoordinator) {
  26978. this.collisionCoordinator.onGeometryDeleted(geometry);
  26979. }
  26980. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26981. return true;
  26982. }
  26983. return false;
  26984. };
  26985. /**
  26986. * Gets the list of geometries attached to the scene
  26987. * @returns an array of Geometry
  26988. */
  26989. Scene.prototype.getGeometries = function () {
  26990. return this._geometries;
  26991. };
  26992. /**
  26993. * Gets the first added mesh found of a given ID
  26994. * @param id defines the id to search for
  26995. * @return the mesh found or null if not found at all
  26996. */
  26997. Scene.prototype.getMeshByID = function (id) {
  26998. for (var index = 0; index < this.meshes.length; index++) {
  26999. if (this.meshes[index].id === id) {
  27000. return this.meshes[index];
  27001. }
  27002. }
  27003. return null;
  27004. };
  27005. /**
  27006. * Gets a list of meshes using their id
  27007. * @param id defines the id to search for
  27008. * @returns a list of meshes
  27009. */
  27010. Scene.prototype.getMeshesByID = function (id) {
  27011. return this.meshes.filter(function (m) {
  27012. return m.id === id;
  27013. });
  27014. };
  27015. /**
  27016. * Gets the first added transform node found of a given ID
  27017. * @param id defines the id to search for
  27018. * @return the found transform node or null if not found at all.
  27019. */
  27020. Scene.prototype.getTransformNodeByID = function (id) {
  27021. for (var index = 0; index < this.transformNodes.length; index++) {
  27022. if (this.transformNodes[index].id === id) {
  27023. return this.transformNodes[index];
  27024. }
  27025. }
  27026. return null;
  27027. };
  27028. /**
  27029. * Gets a list of transform nodes using their id
  27030. * @param id defines the id to search for
  27031. * @returns a list of transform nodes
  27032. */
  27033. Scene.prototype.getTransformNodesByID = function (id) {
  27034. return this.transformNodes.filter(function (m) {
  27035. return m.id === id;
  27036. });
  27037. };
  27038. /**
  27039. * Gets a mesh with its auto-generated unique id
  27040. * @param uniqueId defines the unique id to search for
  27041. * @return the found mesh or null if not found at all.
  27042. */
  27043. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27044. for (var index = 0; index < this.meshes.length; index++) {
  27045. if (this.meshes[index].uniqueId === uniqueId) {
  27046. return this.meshes[index];
  27047. }
  27048. }
  27049. return null;
  27050. };
  27051. /**
  27052. * Gets a the last added mesh using a given id
  27053. * @param id defines the id to search for
  27054. * @return the found mesh or null if not found at all.
  27055. */
  27056. Scene.prototype.getLastMeshByID = function (id) {
  27057. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27058. if (this.meshes[index].id === id) {
  27059. return this.meshes[index];
  27060. }
  27061. }
  27062. return null;
  27063. };
  27064. /**
  27065. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27066. * @param id defines the id to search for
  27067. * @return the found node or null if not found at all
  27068. */
  27069. Scene.prototype.getLastEntryByID = function (id) {
  27070. var index;
  27071. for (index = this.meshes.length - 1; index >= 0; index--) {
  27072. if (this.meshes[index].id === id) {
  27073. return this.meshes[index];
  27074. }
  27075. }
  27076. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27077. if (this.transformNodes[index].id === id) {
  27078. return this.transformNodes[index];
  27079. }
  27080. }
  27081. for (index = this.cameras.length - 1; index >= 0; index--) {
  27082. if (this.cameras[index].id === id) {
  27083. return this.cameras[index];
  27084. }
  27085. }
  27086. for (index = this.lights.length - 1; index >= 0; index--) {
  27087. if (this.lights[index].id === id) {
  27088. return this.lights[index];
  27089. }
  27090. }
  27091. return null;
  27092. };
  27093. /**
  27094. * Gets a node (Mesh, Camera, Light) using a given id
  27095. * @param id defines the id to search for
  27096. * @return the found node or null if not found at all
  27097. */
  27098. Scene.prototype.getNodeByID = function (id) {
  27099. var mesh = this.getMeshByID(id);
  27100. if (mesh) {
  27101. return mesh;
  27102. }
  27103. var light = this.getLightByID(id);
  27104. if (light) {
  27105. return light;
  27106. }
  27107. var camera = this.getCameraByID(id);
  27108. if (camera) {
  27109. return camera;
  27110. }
  27111. var bone = this.getBoneByID(id);
  27112. return bone;
  27113. };
  27114. /**
  27115. * Gets a node (Mesh, Camera, Light) using a given name
  27116. * @param name defines the name to search for
  27117. * @return the found node or null if not found at all.
  27118. */
  27119. Scene.prototype.getNodeByName = function (name) {
  27120. var mesh = this.getMeshByName(name);
  27121. if (mesh) {
  27122. return mesh;
  27123. }
  27124. var light = this.getLightByName(name);
  27125. if (light) {
  27126. return light;
  27127. }
  27128. var camera = this.getCameraByName(name);
  27129. if (camera) {
  27130. return camera;
  27131. }
  27132. var bone = this.getBoneByName(name);
  27133. return bone;
  27134. };
  27135. /**
  27136. * Gets a mesh using a given name
  27137. * @param name defines the name to search for
  27138. * @return the found mesh or null if not found at all.
  27139. */
  27140. Scene.prototype.getMeshByName = function (name) {
  27141. for (var index = 0; index < this.meshes.length; index++) {
  27142. if (this.meshes[index].name === name) {
  27143. return this.meshes[index];
  27144. }
  27145. }
  27146. return null;
  27147. };
  27148. /**
  27149. * Gets a transform node using a given name
  27150. * @param name defines the name to search for
  27151. * @return the found transform node or null if not found at all.
  27152. */
  27153. Scene.prototype.getTransformNodeByName = function (name) {
  27154. for (var index = 0; index < this.transformNodes.length; index++) {
  27155. if (this.transformNodes[index].name === name) {
  27156. return this.transformNodes[index];
  27157. }
  27158. }
  27159. return null;
  27160. };
  27161. /**
  27162. * Gets a sound using a given name
  27163. * @param name defines the name to search for
  27164. * @return the found sound or null if not found at all.
  27165. */
  27166. Scene.prototype.getSoundByName = function (name) {
  27167. var index;
  27168. if (BABYLON.AudioEngine) {
  27169. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27170. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27171. return this.mainSoundTrack.soundCollection[index];
  27172. }
  27173. }
  27174. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27175. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27176. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27177. return this.soundTracks[sdIndex].soundCollection[index];
  27178. }
  27179. }
  27180. }
  27181. }
  27182. return null;
  27183. };
  27184. /**
  27185. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27186. * @param id defines the id to search for
  27187. * @return the found skeleton or null if not found at all.
  27188. */
  27189. Scene.prototype.getLastSkeletonByID = function (id) {
  27190. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27191. if (this.skeletons[index].id === id) {
  27192. return this.skeletons[index];
  27193. }
  27194. }
  27195. return null;
  27196. };
  27197. /**
  27198. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27199. * @param id defines the id to search for
  27200. * @return the found skeleton or null if not found at all.
  27201. */
  27202. Scene.prototype.getSkeletonById = function (id) {
  27203. for (var index = 0; index < this.skeletons.length; index++) {
  27204. if (this.skeletons[index].id === id) {
  27205. return this.skeletons[index];
  27206. }
  27207. }
  27208. return null;
  27209. };
  27210. /**
  27211. * Gets a skeleton using a given name
  27212. * @param name defines the name to search for
  27213. * @return the found skeleton or null if not found at all.
  27214. */
  27215. Scene.prototype.getSkeletonByName = function (name) {
  27216. for (var index = 0; index < this.skeletons.length; index++) {
  27217. if (this.skeletons[index].name === name) {
  27218. return this.skeletons[index];
  27219. }
  27220. }
  27221. return null;
  27222. };
  27223. /**
  27224. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27225. * @param id defines the id to search for
  27226. * @return the found morph target manager or null if not found at all.
  27227. */
  27228. Scene.prototype.getMorphTargetManagerById = function (id) {
  27229. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27230. if (this.morphTargetManagers[index].uniqueId === id) {
  27231. return this.morphTargetManagers[index];
  27232. }
  27233. }
  27234. return null;
  27235. };
  27236. /**
  27237. * Gets a boolean indicating if the given mesh is active
  27238. * @param mesh defines the mesh to look for
  27239. * @returns true if the mesh is in the active list
  27240. */
  27241. Scene.prototype.isActiveMesh = function (mesh) {
  27242. return (this._activeMeshes.indexOf(mesh) !== -1);
  27243. };
  27244. /**
  27245. * Return a the first highlight layer of the scene with a given name.
  27246. * @param name The name of the highlight layer to look for.
  27247. * @return The highlight layer if found otherwise null.
  27248. */
  27249. Scene.prototype.getHighlightLayerByName = function (name) {
  27250. for (var index = 0; index < this.effectLayers.length; index++) {
  27251. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27252. return this.effectLayers[index];
  27253. }
  27254. }
  27255. return null;
  27256. };
  27257. /**
  27258. * Return a the first highlight layer of the scene with a given name.
  27259. * @param name The name of the highlight layer to look for.
  27260. * @return The highlight layer if found otherwise null.
  27261. */
  27262. Scene.prototype.getGlowLayerByName = function (name) {
  27263. for (var index = 0; index < this.effectLayers.length; index++) {
  27264. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27265. return this.effectLayers[index];
  27266. }
  27267. }
  27268. return null;
  27269. };
  27270. Object.defineProperty(Scene.prototype, "uid", {
  27271. /**
  27272. * Return a unique id as a string which can serve as an identifier for the scene
  27273. */
  27274. get: function () {
  27275. if (!this._uid) {
  27276. this._uid = BABYLON.Tools.RandomId();
  27277. }
  27278. return this._uid;
  27279. },
  27280. enumerable: true,
  27281. configurable: true
  27282. });
  27283. /**
  27284. * Add an externaly attached data from its key.
  27285. * This method call will fail and return false, if such key already exists.
  27286. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27287. * @param key the unique key that identifies the data
  27288. * @param data the data object to associate to the key for this Engine instance
  27289. * @return true if no such key were already present and the data was added successfully, false otherwise
  27290. */
  27291. Scene.prototype.addExternalData = function (key, data) {
  27292. if (!this._externalData) {
  27293. this._externalData = new BABYLON.StringDictionary();
  27294. }
  27295. return this._externalData.add(key, data);
  27296. };
  27297. /**
  27298. * Get an externaly attached data from its key
  27299. * @param key the unique key that identifies the data
  27300. * @return the associated data, if present (can be null), or undefined if not present
  27301. */
  27302. Scene.prototype.getExternalData = function (key) {
  27303. if (!this._externalData) {
  27304. return null;
  27305. }
  27306. return this._externalData.get(key);
  27307. };
  27308. /**
  27309. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27310. * @param key the unique key that identifies the data
  27311. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27312. * @return the associated data, can be null if the factory returned null.
  27313. */
  27314. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27315. if (!this._externalData) {
  27316. this._externalData = new BABYLON.StringDictionary();
  27317. }
  27318. return this._externalData.getOrAddWithFactory(key, factory);
  27319. };
  27320. /**
  27321. * Remove an externaly attached data from the Engine instance
  27322. * @param key the unique key that identifies the data
  27323. * @return true if the data was successfully removed, false if it doesn't exist
  27324. */
  27325. Scene.prototype.removeExternalData = function (key) {
  27326. return this._externalData.remove(key);
  27327. };
  27328. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27329. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27330. if (mesh.showSubMeshesBoundingBox) {
  27331. var boundingInfo = subMesh.getBoundingInfo();
  27332. if (boundingInfo !== null && boundingInfo !== undefined) {
  27333. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27334. }
  27335. }
  27336. var material = subMesh.getMaterial();
  27337. if (material !== null && material !== undefined) {
  27338. // Render targets
  27339. if (material.getRenderTargetTextures !== undefined) {
  27340. if (this._processedMaterials.indexOf(material) === -1) {
  27341. this._processedMaterials.push(material);
  27342. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27343. }
  27344. }
  27345. // Dispatch
  27346. this._activeIndices.addCount(subMesh.indexCount, false);
  27347. this._renderingManager.dispatch(subMesh, mesh, material);
  27348. }
  27349. }
  27350. };
  27351. /**
  27352. * Clear the processed materials smart array preventing retention point in material dispose.
  27353. */
  27354. Scene.prototype.freeProcessedMaterials = function () {
  27355. this._processedMaterials.dispose();
  27356. };
  27357. /**
  27358. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27359. */
  27360. Scene.prototype.freeActiveMeshes = function () {
  27361. this._activeMeshes.dispose();
  27362. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27363. this.activeCamera._activeMeshes.dispose();
  27364. }
  27365. if (this.activeCameras) {
  27366. for (var i = 0; i < this.activeCameras.length; i++) {
  27367. var activeCamera = this.activeCameras[i];
  27368. if (activeCamera && activeCamera._activeMeshes) {
  27369. activeCamera._activeMeshes.dispose();
  27370. }
  27371. }
  27372. }
  27373. };
  27374. /**
  27375. * Clear the info related to rendering groups preventing retention points during dispose.
  27376. */
  27377. Scene.prototype.freeRenderingGroups = function () {
  27378. if (this._renderingManager) {
  27379. this._renderingManager.freeRenderingGroups();
  27380. }
  27381. if (this.textures) {
  27382. for (var i = 0; i < this.textures.length; i++) {
  27383. var texture = this.textures[i];
  27384. if (texture && texture.renderList) {
  27385. texture.freeRenderingGroups();
  27386. }
  27387. }
  27388. }
  27389. };
  27390. /** @hidden */
  27391. Scene.prototype._isInIntermediateRendering = function () {
  27392. return this._intermediateRendering;
  27393. };
  27394. /**
  27395. * Defines the current active mesh candidate provider
  27396. * @param provider defines the provider to use
  27397. */
  27398. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27399. this._activeMeshCandidateProvider = provider;
  27400. };
  27401. /**
  27402. * Gets the current active mesh candidate provider
  27403. * @returns the current active mesh candidate provider
  27404. */
  27405. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27406. return this._activeMeshCandidateProvider;
  27407. };
  27408. /**
  27409. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27410. * @returns the current scene
  27411. */
  27412. Scene.prototype.freezeActiveMeshes = function () {
  27413. if (!this.activeCamera) {
  27414. return this;
  27415. }
  27416. if (!this._frustumPlanes) {
  27417. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27418. }
  27419. this._evaluateActiveMeshes();
  27420. this._activeMeshesFrozen = true;
  27421. return this;
  27422. };
  27423. /**
  27424. * Use this function to restart evaluating active meshes on every frame
  27425. * @returns the current scene
  27426. */
  27427. Scene.prototype.unfreezeActiveMeshes = function () {
  27428. this._activeMeshesFrozen = false;
  27429. return this;
  27430. };
  27431. Scene.prototype._evaluateActiveMeshes = function () {
  27432. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27433. return;
  27434. }
  27435. if (!this.activeCamera) {
  27436. return;
  27437. }
  27438. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27439. this.activeCamera._activeMeshes.reset();
  27440. this._activeMeshes.reset();
  27441. this._renderingManager.reset();
  27442. this._processedMaterials.reset();
  27443. this._activeParticleSystems.reset();
  27444. this._activeSkeletons.reset();
  27445. this._softwareSkinnedMeshes.reset();
  27446. if (this._boundingBoxRenderer) {
  27447. this._boundingBoxRenderer.reset();
  27448. }
  27449. // Meshes
  27450. var meshes;
  27451. var len;
  27452. var checkIsEnabled = true;
  27453. // Determine mesh candidates
  27454. if (this._activeMeshCandidateProvider !== undefined) {
  27455. // Use _activeMeshCandidateProvider
  27456. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27457. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27458. if (meshes !== undefined) {
  27459. len = meshes.length;
  27460. }
  27461. else {
  27462. len = 0;
  27463. }
  27464. }
  27465. else if (this._selectionOctree !== undefined) {
  27466. // Octree
  27467. var selection = this._selectionOctree.select(this._frustumPlanes);
  27468. meshes = selection.data;
  27469. len = selection.length;
  27470. }
  27471. else {
  27472. // Full scene traversal
  27473. len = this.meshes.length;
  27474. meshes = this.meshes;
  27475. }
  27476. // Check each mesh
  27477. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27478. mesh = meshes[meshIndex];
  27479. if (mesh.isBlocked) {
  27480. continue;
  27481. }
  27482. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27483. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27484. continue;
  27485. }
  27486. mesh.computeWorldMatrix();
  27487. // Intersections
  27488. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27489. this._meshesForIntersections.pushNoDuplicate(mesh);
  27490. }
  27491. // Switch to current LOD
  27492. meshLOD = mesh.getLOD(this.activeCamera);
  27493. if (meshLOD === undefined || meshLOD === null) {
  27494. continue;
  27495. }
  27496. mesh._preActivate();
  27497. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27498. this._activeMeshes.push(mesh);
  27499. this.activeCamera._activeMeshes.push(mesh);
  27500. mesh._activate(this._renderId);
  27501. if (meshLOD !== mesh) {
  27502. meshLOD._activate(this._renderId);
  27503. }
  27504. this._activeMesh(mesh, meshLOD);
  27505. }
  27506. }
  27507. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27508. // Particle systems
  27509. if (this.particlesEnabled) {
  27510. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27511. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27512. var particleSystem = this.particleSystems[particleIndex];
  27513. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27514. continue;
  27515. }
  27516. var emitter = particleSystem.emitter;
  27517. if (!emitter.position || emitter.isEnabled()) {
  27518. this._activeParticleSystems.push(particleSystem);
  27519. particleSystem.animate();
  27520. this._renderingManager.dispatchParticles(particleSystem);
  27521. }
  27522. }
  27523. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27524. }
  27525. };
  27526. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27527. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27528. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27529. mesh.skeleton.prepare();
  27530. }
  27531. if (!mesh.computeBonesUsingShaders) {
  27532. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27533. }
  27534. }
  27535. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27536. var boundingInfo = sourceMesh.getBoundingInfo();
  27537. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27538. }
  27539. if (mesh !== undefined && mesh !== null
  27540. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27541. // Submeshes Octrees
  27542. var len;
  27543. var subMeshes;
  27544. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27545. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27546. len = intersections.length;
  27547. subMeshes = intersections.data;
  27548. }
  27549. else {
  27550. subMeshes = mesh.subMeshes;
  27551. len = subMeshes.length;
  27552. }
  27553. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27554. subMesh = subMeshes[subIndex];
  27555. this._evaluateSubMesh(subMesh, mesh);
  27556. }
  27557. }
  27558. };
  27559. /**
  27560. * Update the transform matrix to update from the current active camera
  27561. * @param force defines a boolean used to force the update even if cache is up to date
  27562. */
  27563. Scene.prototype.updateTransformMatrix = function (force) {
  27564. if (!this.activeCamera) {
  27565. return;
  27566. }
  27567. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27568. };
  27569. /**
  27570. * 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)
  27571. * @param alternateCamera defines the camera to use
  27572. */
  27573. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27574. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27575. };
  27576. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27577. if (camera && camera._skipRendering) {
  27578. return;
  27579. }
  27580. var engine = this._engine;
  27581. this.activeCamera = camera;
  27582. if (!this.activeCamera)
  27583. throw new Error("Active camera not set");
  27584. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27585. // Viewport
  27586. engine.setViewport(this.activeCamera.viewport);
  27587. // Camera
  27588. this.resetCachedMaterial();
  27589. this._renderId++;
  27590. this.updateTransformMatrix();
  27591. if (camera._alternateCamera) {
  27592. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27593. this._alternateRendering = true;
  27594. }
  27595. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27596. // Meshes
  27597. this._evaluateActiveMeshes();
  27598. // Software skinning
  27599. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27600. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27601. mesh.applySkeleton(mesh.skeleton);
  27602. }
  27603. // Render targets
  27604. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27605. var needsRestoreFrameBuffer = false;
  27606. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27607. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27608. }
  27609. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27610. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27611. }
  27612. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27613. this._intermediateRendering = true;
  27614. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27615. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27616. var renderTarget = this._renderTargets.data[renderIndex];
  27617. if (renderTarget._shouldRender()) {
  27618. this._renderId++;
  27619. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27620. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27621. }
  27622. }
  27623. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27624. this._intermediateRendering = false;
  27625. this._renderId++;
  27626. needsRestoreFrameBuffer = true; // Restore back buffer
  27627. }
  27628. // Render EffecttLayer Texture
  27629. var stencilState = this._engine.getStencilBuffer();
  27630. var renderEffects = false;
  27631. var needStencil = false;
  27632. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27633. this._intermediateRendering = true;
  27634. for (var i = 0; i < this.effectLayers.length; i++) {
  27635. var effectLayer = this.effectLayers[i];
  27636. if (effectLayer.shouldRender() &&
  27637. (!effectLayer.camera ||
  27638. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27639. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27640. renderEffects = true;
  27641. needStencil = needStencil || effectLayer.needStencil();
  27642. var renderTarget = effectLayer._mainTexture;
  27643. if (renderTarget._shouldRender()) {
  27644. this._renderId++;
  27645. renderTarget.render(false, false);
  27646. needsRestoreFrameBuffer = true;
  27647. }
  27648. }
  27649. }
  27650. this._intermediateRendering = false;
  27651. this._renderId++;
  27652. }
  27653. if (needsRestoreFrameBuffer) {
  27654. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27655. }
  27656. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27657. // Prepare Frame
  27658. if (this.postProcessManager) {
  27659. this.postProcessManager._prepareFrame();
  27660. }
  27661. // Backgrounds
  27662. var layerIndex;
  27663. var layer;
  27664. if (this.layers.length) {
  27665. engine.setDepthBuffer(false);
  27666. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27667. layer = this.layers[layerIndex];
  27668. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27669. layer.render();
  27670. }
  27671. }
  27672. engine.setDepthBuffer(true);
  27673. }
  27674. // Activate effect Layer stencil
  27675. if (needStencil) {
  27676. this._engine.setStencilBuffer(true);
  27677. }
  27678. // Render
  27679. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27680. this._renderingManager.render(null, null, true, true);
  27681. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27682. // Restore effect Layer stencil
  27683. if (needStencil) {
  27684. this._engine.setStencilBuffer(stencilState);
  27685. }
  27686. // Bounding boxes
  27687. if (this._boundingBoxRenderer) {
  27688. this._boundingBoxRenderer.render();
  27689. }
  27690. // Lens flares
  27691. if (this.lensFlaresEnabled) {
  27692. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27693. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27694. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27695. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27696. lensFlareSystem.render();
  27697. }
  27698. }
  27699. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27700. }
  27701. // Effect Layer
  27702. if (renderEffects) {
  27703. engine.setDepthBuffer(false);
  27704. for (var i = 0; i < this.effectLayers.length; i++) {
  27705. if (this.effectLayers[i].shouldRender()) {
  27706. this.effectLayers[i].render();
  27707. }
  27708. }
  27709. engine.setDepthBuffer(true);
  27710. }
  27711. // Foregrounds
  27712. if (this.layers.length) {
  27713. engine.setDepthBuffer(false);
  27714. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27715. layer = this.layers[layerIndex];
  27716. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27717. layer.render();
  27718. }
  27719. }
  27720. engine.setDepthBuffer(true);
  27721. }
  27722. // Finalize frame
  27723. if (this.postProcessManager) {
  27724. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27725. }
  27726. // Reset some special arrays
  27727. this._renderTargets.reset();
  27728. this._alternateRendering = false;
  27729. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27730. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27731. };
  27732. Scene.prototype._processSubCameras = function (camera) {
  27733. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27734. this._renderForCamera(camera);
  27735. return;
  27736. }
  27737. // rig cameras
  27738. for (var index = 0; index < camera._rigCameras.length; index++) {
  27739. this._renderForCamera(camera._rigCameras[index], camera);
  27740. }
  27741. this.activeCamera = camera;
  27742. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27743. };
  27744. Scene.prototype._checkIntersections = function () {
  27745. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27746. var sourceMesh = this._meshesForIntersections.data[index];
  27747. if (!sourceMesh.actionManager) {
  27748. continue;
  27749. }
  27750. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27751. var action = sourceMesh.actionManager.actions[actionIndex];
  27752. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27753. var parameters = action.getTriggerParameter();
  27754. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27755. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27756. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27757. if (areIntersecting && currentIntersectionInProgress === -1) {
  27758. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27759. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27760. sourceMesh._intersectionsInProgress.push(otherMesh);
  27761. }
  27762. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27763. sourceMesh._intersectionsInProgress.push(otherMesh);
  27764. }
  27765. }
  27766. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27767. //They intersected, and now they don't.
  27768. //is this trigger an exit trigger? execute an event.
  27769. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27770. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27771. }
  27772. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27773. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27774. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27775. return otherMesh === parameterMesh;
  27776. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27777. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27778. }
  27779. }
  27780. }
  27781. }
  27782. }
  27783. };
  27784. /**
  27785. * Render the scene
  27786. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27787. */
  27788. Scene.prototype.render = function (updateCameras) {
  27789. if (updateCameras === void 0) { updateCameras = true; }
  27790. if (this.isDisposed) {
  27791. return;
  27792. }
  27793. this._activeParticles.fetchNewFrame();
  27794. this._totalVertices.fetchNewFrame();
  27795. this._activeIndices.fetchNewFrame();
  27796. this._activeBones.fetchNewFrame();
  27797. this._meshesForIntersections.reset();
  27798. this.resetCachedMaterial();
  27799. this.onBeforeAnimationsObservable.notifyObservers(this);
  27800. // Actions
  27801. if (this.actionManager) {
  27802. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27803. }
  27804. //Simplification Queue
  27805. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27806. this.simplificationQueue.executeNext();
  27807. }
  27808. if (this._engine.isDeterministicLockStep()) {
  27809. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27810. var defaultFPS = (60.0 / 1000.0);
  27811. var defaultFrameTime = 1000 / 60; // frame time in MS
  27812. if (this._physicsEngine) {
  27813. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27814. }
  27815. var stepsTaken = 0;
  27816. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27817. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27818. internalSteps = Math.min(internalSteps, maxSubSteps);
  27819. do {
  27820. this.onBeforeStepObservable.notifyObservers(this);
  27821. // Animations
  27822. this._animationRatio = defaultFrameTime * defaultFPS;
  27823. this._animate();
  27824. this.onAfterAnimationsObservable.notifyObservers(this);
  27825. // Physics
  27826. if (this._physicsEngine) {
  27827. this.onBeforePhysicsObservable.notifyObservers(this);
  27828. this._physicsEngine._step(defaultFrameTime / 1000);
  27829. this.onAfterPhysicsObservable.notifyObservers(this);
  27830. }
  27831. this.onAfterStepObservable.notifyObservers(this);
  27832. this._currentStepId++;
  27833. stepsTaken++;
  27834. deltaTime -= defaultFrameTime;
  27835. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27836. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27837. }
  27838. else {
  27839. // Animations
  27840. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27841. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27842. this._animate();
  27843. this.onAfterAnimationsObservable.notifyObservers(this);
  27844. // Physics
  27845. if (this._physicsEngine) {
  27846. this.onBeforePhysicsObservable.notifyObservers(this);
  27847. this._physicsEngine._step(deltaTime / 1000.0);
  27848. this.onAfterPhysicsObservable.notifyObservers(this);
  27849. }
  27850. }
  27851. // update gamepad manager
  27852. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27853. this._gamepadManager._checkGamepadsStatus();
  27854. }
  27855. // Update Cameras
  27856. if (updateCameras) {
  27857. if (this.activeCameras.length > 0) {
  27858. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27859. var camera = this.activeCameras[cameraIndex];
  27860. camera.update();
  27861. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27862. // rig cameras
  27863. for (var index = 0; index < camera._rigCameras.length; index++) {
  27864. camera._rigCameras[index].update();
  27865. }
  27866. }
  27867. }
  27868. }
  27869. else if (this.activeCamera) {
  27870. this.activeCamera.update();
  27871. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27872. // rig cameras
  27873. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27874. this.activeCamera._rigCameras[index].update();
  27875. }
  27876. }
  27877. }
  27878. }
  27879. // Before render
  27880. this.onBeforeRenderObservable.notifyObservers(this);
  27881. // Customs render targets
  27882. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27883. var engine = this.getEngine();
  27884. var currentActiveCamera = this.activeCamera;
  27885. if (this.renderTargetsEnabled) {
  27886. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27887. this._intermediateRendering = true;
  27888. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27889. var renderTarget = this.customRenderTargets[customIndex];
  27890. if (renderTarget._shouldRender()) {
  27891. this._renderId++;
  27892. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27893. if (!this.activeCamera)
  27894. throw new Error("Active camera not set");
  27895. // Viewport
  27896. engine.setViewport(this.activeCamera.viewport);
  27897. // Camera
  27898. this.updateTransformMatrix();
  27899. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27900. }
  27901. }
  27902. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27903. this._intermediateRendering = false;
  27904. this._renderId++;
  27905. }
  27906. // Restore back buffer
  27907. if (this.customRenderTargets.length > 0) {
  27908. engine.restoreDefaultFramebuffer();
  27909. }
  27910. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27911. this.activeCamera = currentActiveCamera;
  27912. // Procedural textures
  27913. if (this.proceduralTexturesEnabled) {
  27914. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27915. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27916. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27917. if (proceduralTexture._shouldRender()) {
  27918. proceduralTexture.render();
  27919. }
  27920. }
  27921. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27922. }
  27923. // Clear
  27924. if (this.autoClearDepthAndStencil || this.autoClear) {
  27925. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27926. }
  27927. // Shadows
  27928. if (this.shadowsEnabled) {
  27929. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27930. var light = this.lights[lightIndex];
  27931. var shadowGenerator = light.getShadowGenerator();
  27932. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27933. var shadowMap = (shadowGenerator.getShadowMap());
  27934. if (this.textures.indexOf(shadowMap) !== -1) {
  27935. this._renderTargets.push(shadowMap);
  27936. }
  27937. }
  27938. }
  27939. }
  27940. // Depth renderer
  27941. for (var key in this._depthRenderer) {
  27942. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27943. }
  27944. // Geometry renderer
  27945. if (this._geometryBufferRenderer) {
  27946. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27947. }
  27948. // RenderPipeline
  27949. if (this._postProcessRenderPipelineManager) {
  27950. this._postProcessRenderPipelineManager.update();
  27951. }
  27952. // Multi-cameras?
  27953. if (this.activeCameras.length > 0) {
  27954. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27955. if (cameraIndex > 0) {
  27956. this._engine.clear(null, false, true, true);
  27957. }
  27958. this._processSubCameras(this.activeCameras[cameraIndex]);
  27959. }
  27960. }
  27961. else {
  27962. if (!this.activeCamera) {
  27963. throw new Error("No camera defined");
  27964. }
  27965. this._processSubCameras(this.activeCamera);
  27966. }
  27967. // Intersection checks
  27968. this._checkIntersections();
  27969. // Update the audio listener attached to the camera
  27970. if (BABYLON.AudioEngine) {
  27971. this._updateAudioParameters();
  27972. }
  27973. // After render
  27974. if (this.afterRender) {
  27975. this.afterRender();
  27976. }
  27977. this.onAfterRenderObservable.notifyObservers(this);
  27978. // Cleaning
  27979. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27980. var data = this._toBeDisposed.data[index];
  27981. if (data) {
  27982. data.dispose();
  27983. }
  27984. this._toBeDisposed[index] = null;
  27985. }
  27986. this._toBeDisposed.reset();
  27987. if (this.dumpNextRenderTargets) {
  27988. this.dumpNextRenderTargets = false;
  27989. }
  27990. this._activeBones.addCount(0, true);
  27991. this._activeIndices.addCount(0, true);
  27992. this._activeParticles.addCount(0, true);
  27993. };
  27994. Scene.prototype._updateAudioParameters = function () {
  27995. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27996. return;
  27997. }
  27998. var listeningCamera;
  27999. var audioEngine = BABYLON.Engine.audioEngine;
  28000. if (this.activeCameras.length > 0) {
  28001. listeningCamera = this.activeCameras[0];
  28002. }
  28003. else {
  28004. listeningCamera = this.activeCamera;
  28005. }
  28006. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28007. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28008. // for VR cameras
  28009. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28010. listeningCamera = listeningCamera.rigCameras[0];
  28011. }
  28012. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28013. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28014. cameraDirection.normalize();
  28015. // To avoid some errors on GearVR
  28016. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28017. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28018. }
  28019. var i;
  28020. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28021. var sound = this.mainSoundTrack.soundCollection[i];
  28022. if (sound.useCustomAttenuation) {
  28023. sound.updateDistanceFromListener();
  28024. }
  28025. }
  28026. for (i = 0; i < this.soundTracks.length; i++) {
  28027. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28028. sound = this.soundTracks[i].soundCollection[j];
  28029. if (sound.useCustomAttenuation) {
  28030. sound.updateDistanceFromListener();
  28031. }
  28032. }
  28033. }
  28034. }
  28035. };
  28036. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28037. // Audio
  28038. /**
  28039. * Gets or sets if audio support is enabled
  28040. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28041. */
  28042. get: function () {
  28043. return this._audioEnabled;
  28044. },
  28045. set: function (value) {
  28046. this._audioEnabled = value;
  28047. if (BABYLON.AudioEngine) {
  28048. if (this._audioEnabled) {
  28049. this._enableAudio();
  28050. }
  28051. else {
  28052. this._disableAudio();
  28053. }
  28054. }
  28055. },
  28056. enumerable: true,
  28057. configurable: true
  28058. });
  28059. Scene.prototype._disableAudio = function () {
  28060. var i;
  28061. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28062. this.mainSoundTrack.soundCollection[i].pause();
  28063. }
  28064. for (i = 0; i < this.soundTracks.length; i++) {
  28065. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28066. this.soundTracks[i].soundCollection[j].pause();
  28067. }
  28068. }
  28069. };
  28070. Scene.prototype._enableAudio = function () {
  28071. var i;
  28072. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28073. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28074. this.mainSoundTrack.soundCollection[i].play();
  28075. }
  28076. }
  28077. for (i = 0; i < this.soundTracks.length; i++) {
  28078. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28079. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28080. this.soundTracks[i].soundCollection[j].play();
  28081. }
  28082. }
  28083. }
  28084. };
  28085. Object.defineProperty(Scene.prototype, "headphone", {
  28086. /**
  28087. * Gets or sets if audio will be output to headphones
  28088. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28089. */
  28090. get: function () {
  28091. return this._headphone;
  28092. },
  28093. set: function (value) {
  28094. this._headphone = value;
  28095. if (BABYLON.AudioEngine) {
  28096. if (this._headphone) {
  28097. this._switchAudioModeForHeadphones();
  28098. }
  28099. else {
  28100. this._switchAudioModeForNormalSpeakers();
  28101. }
  28102. }
  28103. },
  28104. enumerable: true,
  28105. configurable: true
  28106. });
  28107. Scene.prototype._switchAudioModeForHeadphones = function () {
  28108. this.mainSoundTrack.switchPanningModelToHRTF();
  28109. for (var i = 0; i < this.soundTracks.length; i++) {
  28110. this.soundTracks[i].switchPanningModelToHRTF();
  28111. }
  28112. };
  28113. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28114. this.mainSoundTrack.switchPanningModelToEqualPower();
  28115. for (var i = 0; i < this.soundTracks.length; i++) {
  28116. this.soundTracks[i].switchPanningModelToEqualPower();
  28117. }
  28118. };
  28119. /**
  28120. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28121. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28122. * @returns the created depth renderer
  28123. */
  28124. Scene.prototype.enableDepthRenderer = function (camera) {
  28125. camera = camera || this.activeCamera;
  28126. if (!camera) {
  28127. throw "No camera available to enable depth renderer";
  28128. }
  28129. if (!this._depthRenderer[camera.id]) {
  28130. var textureType = 0;
  28131. if (this._engine.getCaps().textureHalfFloatRender) {
  28132. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28133. }
  28134. else if (this._engine.getCaps().textureFloatRender) {
  28135. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28136. }
  28137. else {
  28138. throw "Depth renderer does not support int texture type";
  28139. }
  28140. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28141. }
  28142. return this._depthRenderer[camera.id];
  28143. };
  28144. /**
  28145. * Disables a depth renderer for a given camera
  28146. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28147. */
  28148. Scene.prototype.disableDepthRenderer = function (camera) {
  28149. camera = camera || this.activeCamera;
  28150. if (!camera || !this._depthRenderer[camera.id]) {
  28151. return;
  28152. }
  28153. this._depthRenderer[camera.id].dispose();
  28154. delete this._depthRenderer[camera.id];
  28155. };
  28156. /**
  28157. * Enables a GeometryBufferRender and associates it with the scene
  28158. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28159. * @returns the GeometryBufferRenderer
  28160. */
  28161. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28162. if (ratio === void 0) { ratio = 1; }
  28163. if (this._geometryBufferRenderer) {
  28164. return this._geometryBufferRenderer;
  28165. }
  28166. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28167. if (!this._geometryBufferRenderer.isSupported) {
  28168. this._geometryBufferRenderer = null;
  28169. }
  28170. return this._geometryBufferRenderer;
  28171. };
  28172. /**
  28173. * Disables the GeometryBufferRender associated with the scene
  28174. */
  28175. Scene.prototype.disableGeometryBufferRenderer = function () {
  28176. if (!this._geometryBufferRenderer) {
  28177. return;
  28178. }
  28179. this._geometryBufferRenderer.dispose();
  28180. this._geometryBufferRenderer = null;
  28181. };
  28182. /**
  28183. * Freeze all materials
  28184. * A frozen material will not be updatable but should be faster to render
  28185. */
  28186. Scene.prototype.freezeMaterials = function () {
  28187. for (var i = 0; i < this.materials.length; i++) {
  28188. this.materials[i].freeze();
  28189. }
  28190. };
  28191. /**
  28192. * Unfreeze all materials
  28193. * A frozen material will not be updatable but should be faster to render
  28194. */
  28195. Scene.prototype.unfreezeMaterials = function () {
  28196. for (var i = 0; i < this.materials.length; i++) {
  28197. this.materials[i].unfreeze();
  28198. }
  28199. };
  28200. /**
  28201. * Releases all held ressources
  28202. */
  28203. Scene.prototype.dispose = function () {
  28204. this.beforeRender = null;
  28205. this.afterRender = null;
  28206. this.skeletons = [];
  28207. this.morphTargetManagers = [];
  28208. this.importedMeshesFiles = new Array();
  28209. this.stopAllAnimations();
  28210. this.resetCachedMaterial();
  28211. for (var key in this._depthRenderer) {
  28212. this._depthRenderer[key].dispose();
  28213. }
  28214. if (this._gamepadManager) {
  28215. this._gamepadManager.dispose();
  28216. this._gamepadManager = null;
  28217. }
  28218. // Smart arrays
  28219. if (this.activeCamera) {
  28220. this.activeCamera._activeMeshes.dispose();
  28221. this.activeCamera = null;
  28222. }
  28223. this._activeMeshes.dispose();
  28224. this._renderingManager.dispose();
  28225. this._processedMaterials.dispose();
  28226. this._activeParticleSystems.dispose();
  28227. this._activeSkeletons.dispose();
  28228. this._softwareSkinnedMeshes.dispose();
  28229. this._renderTargets.dispose();
  28230. this._registeredForLateAnimationBindings.dispose();
  28231. if (this._boundingBoxRenderer) {
  28232. this._boundingBoxRenderer.dispose();
  28233. }
  28234. this._meshesForIntersections.dispose();
  28235. this._toBeDisposed.dispose();
  28236. // Abort active requests
  28237. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28238. var request = _a[_i];
  28239. request.abort();
  28240. }
  28241. // Debug layer
  28242. if (this._debugLayer) {
  28243. this._debugLayer.hide();
  28244. }
  28245. // Events
  28246. this.onDisposeObservable.notifyObservers(this);
  28247. this.onDisposeObservable.clear();
  28248. this.onBeforeRenderObservable.clear();
  28249. this.onAfterRenderObservable.clear();
  28250. this.onBeforeRenderTargetsRenderObservable.clear();
  28251. this.onAfterRenderTargetsRenderObservable.clear();
  28252. this.onAfterStepObservable.clear();
  28253. this.onBeforeStepObservable.clear();
  28254. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28255. this.onAfterActiveMeshesEvaluationObservable.clear();
  28256. this.onBeforeParticlesRenderingObservable.clear();
  28257. this.onAfterParticlesRenderingObservable.clear();
  28258. this.onBeforeSpritesRenderingObservable.clear();
  28259. this.onAfterSpritesRenderingObservable.clear();
  28260. this.onBeforeDrawPhaseObservable.clear();
  28261. this.onAfterDrawPhaseObservable.clear();
  28262. this.onBeforePhysicsObservable.clear();
  28263. this.onAfterPhysicsObservable.clear();
  28264. this.onBeforeAnimationsObservable.clear();
  28265. this.onAfterAnimationsObservable.clear();
  28266. this.onDataLoadedObservable.clear();
  28267. this.detachControl();
  28268. // Release sounds & sounds tracks
  28269. if (BABYLON.AudioEngine) {
  28270. this.disposeSounds();
  28271. }
  28272. // VR Helper
  28273. if (this.VRHelper) {
  28274. this.VRHelper.dispose();
  28275. }
  28276. // Detach cameras
  28277. var canvas = this._engine.getRenderingCanvas();
  28278. if (canvas) {
  28279. var index;
  28280. for (index = 0; index < this.cameras.length; index++) {
  28281. this.cameras[index].detachControl(canvas);
  28282. }
  28283. }
  28284. // Release animation groups
  28285. while (this.animationGroups.length) {
  28286. this.animationGroups[0].dispose();
  28287. }
  28288. // Release lights
  28289. while (this.lights.length) {
  28290. this.lights[0].dispose();
  28291. }
  28292. // Release meshes
  28293. while (this.meshes.length) {
  28294. this.meshes[0].dispose(true);
  28295. }
  28296. while (this.transformNodes.length) {
  28297. this.removeTransformNode(this.transformNodes[0]);
  28298. }
  28299. // Release cameras
  28300. while (this.cameras.length) {
  28301. this.cameras[0].dispose();
  28302. }
  28303. // Release materials
  28304. if (this.defaultMaterial) {
  28305. this.defaultMaterial.dispose();
  28306. }
  28307. while (this.multiMaterials.length) {
  28308. this.multiMaterials[0].dispose();
  28309. }
  28310. while (this.materials.length) {
  28311. this.materials[0].dispose();
  28312. }
  28313. // Release particles
  28314. while (this.particleSystems.length) {
  28315. this.particleSystems[0].dispose();
  28316. }
  28317. // Release sprites
  28318. while (this.spriteManagers.length) {
  28319. this.spriteManagers[0].dispose();
  28320. }
  28321. // Release postProcesses
  28322. while (this.postProcesses.length) {
  28323. this.postProcesses[0].dispose();
  28324. }
  28325. // Release layers
  28326. while (this.layers.length) {
  28327. this.layers[0].dispose();
  28328. }
  28329. while (this.effectLayers.length) {
  28330. this.effectLayers[0].dispose();
  28331. }
  28332. // Release textures
  28333. while (this.textures.length) {
  28334. this.textures[0].dispose();
  28335. }
  28336. // Release UBO
  28337. this._sceneUbo.dispose();
  28338. if (this._alternateSceneUbo) {
  28339. this._alternateSceneUbo.dispose();
  28340. }
  28341. // Post-processes
  28342. this.postProcessManager.dispose();
  28343. if (this._postProcessRenderPipelineManager) {
  28344. this._postProcessRenderPipelineManager.dispose();
  28345. }
  28346. // Physics
  28347. if (this._physicsEngine) {
  28348. this.disablePhysicsEngine();
  28349. }
  28350. // Remove from engine
  28351. index = this._engine.scenes.indexOf(this);
  28352. if (index > -1) {
  28353. this._engine.scenes.splice(index, 1);
  28354. }
  28355. this._engine.wipeCaches(true);
  28356. this._isDisposed = true;
  28357. };
  28358. Object.defineProperty(Scene.prototype, "isDisposed", {
  28359. /**
  28360. * Gets if the scene is already disposed
  28361. */
  28362. get: function () {
  28363. return this._isDisposed;
  28364. },
  28365. enumerable: true,
  28366. configurable: true
  28367. });
  28368. /**
  28369. * Releases sounds & soundtracks
  28370. */
  28371. Scene.prototype.disposeSounds = function () {
  28372. if (!this._mainSoundTrack) {
  28373. return;
  28374. }
  28375. this.mainSoundTrack.dispose();
  28376. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28377. this.soundTracks[scIndex].dispose();
  28378. }
  28379. };
  28380. /**
  28381. * Call this function to reduce memory footprint of the scene.
  28382. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28383. */
  28384. Scene.prototype.clearCachedVertexData = function () {
  28385. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28386. var mesh = this.meshes[meshIndex];
  28387. var geometry = mesh.geometry;
  28388. if (geometry) {
  28389. geometry._indices = [];
  28390. for (var vbName in geometry._vertexBuffers) {
  28391. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28392. continue;
  28393. }
  28394. geometry._vertexBuffers[vbName]._buffer._data = null;
  28395. }
  28396. }
  28397. }
  28398. };
  28399. /**
  28400. * This function will remove the local cached buffer data from texture.
  28401. * It will save memory but will prevent the texture from being rebuilt
  28402. */
  28403. Scene.prototype.cleanCachedTextureBuffer = function () {
  28404. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28405. var baseTexture = _a[_i];
  28406. var buffer = baseTexture._buffer;
  28407. if (buffer) {
  28408. baseTexture._buffer = null;
  28409. }
  28410. }
  28411. };
  28412. // Octrees
  28413. /**
  28414. * Get the world extend vectors with an optional filter
  28415. *
  28416. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28417. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28418. */
  28419. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28420. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28421. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28422. filterPredicate = filterPredicate || (function () { return true; });
  28423. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28424. mesh.computeWorldMatrix(true);
  28425. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28426. return;
  28427. }
  28428. var boundingInfo = mesh.getBoundingInfo();
  28429. var minBox = boundingInfo.boundingBox.minimumWorld;
  28430. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28431. BABYLON.Tools.CheckExtends(minBox, min, max);
  28432. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28433. });
  28434. return {
  28435. min: min,
  28436. max: max
  28437. };
  28438. };
  28439. /**
  28440. * Creates or updates the octree used to boost selection (picking)
  28441. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28442. * @param maxCapacity defines the maximum capacity per leaf
  28443. * @param maxDepth defines the maximum depth of the octree
  28444. * @returns an octree of AbstractMesh
  28445. */
  28446. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28447. if (maxCapacity === void 0) { maxCapacity = 64; }
  28448. if (maxDepth === void 0) { maxDepth = 2; }
  28449. if (!this._selectionOctree) {
  28450. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28451. }
  28452. var worldExtends = this.getWorldExtends();
  28453. // Update octree
  28454. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28455. return this._selectionOctree;
  28456. };
  28457. // Picking
  28458. /**
  28459. * Creates a ray that can be used to pick in the scene
  28460. * @param x defines the x coordinate of the origin (on-screen)
  28461. * @param y defines the y coordinate of the origin (on-screen)
  28462. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28463. * @param camera defines the camera to use for the picking
  28464. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28465. * @returns a Ray
  28466. */
  28467. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28468. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28469. var result = BABYLON.Ray.Zero();
  28470. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28471. return result;
  28472. };
  28473. /**
  28474. * Creates a ray that can be used to pick in the scene
  28475. * @param x defines the x coordinate of the origin (on-screen)
  28476. * @param y defines the y coordinate of the origin (on-screen)
  28477. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28478. * @param result defines the ray where to store the picking ray
  28479. * @param camera defines the camera to use for the picking
  28480. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28481. * @returns the current scene
  28482. */
  28483. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28484. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28485. var engine = this._engine;
  28486. if (!camera) {
  28487. if (!this.activeCamera)
  28488. throw new Error("Active camera not set");
  28489. camera = this.activeCamera;
  28490. }
  28491. var cameraViewport = camera.viewport;
  28492. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28493. // Moving coordinates to local viewport world
  28494. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28495. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28496. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28497. return this;
  28498. };
  28499. /**
  28500. * Creates a ray that can be used to pick in the scene
  28501. * @param x defines the x coordinate of the origin (on-screen)
  28502. * @param y defines the y coordinate of the origin (on-screen)
  28503. * @param camera defines the camera to use for the picking
  28504. * @returns a Ray
  28505. */
  28506. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28507. var result = BABYLON.Ray.Zero();
  28508. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28509. return result;
  28510. };
  28511. /**
  28512. * Creates a ray that can be used to pick in the scene
  28513. * @param x defines the x coordinate of the origin (on-screen)
  28514. * @param y defines the y coordinate of the origin (on-screen)
  28515. * @param result defines the ray where to store the picking ray
  28516. * @param camera defines the camera to use for the picking
  28517. * @returns the current scene
  28518. */
  28519. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28520. if (!BABYLON.PickingInfo) {
  28521. return this;
  28522. }
  28523. var engine = this._engine;
  28524. if (!camera) {
  28525. if (!this.activeCamera)
  28526. throw new Error("Active camera not set");
  28527. camera = this.activeCamera;
  28528. }
  28529. var cameraViewport = camera.viewport;
  28530. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28531. var identity = BABYLON.Matrix.Identity();
  28532. // Moving coordinates to local viewport world
  28533. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28534. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28535. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28536. return this;
  28537. };
  28538. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28539. if (!BABYLON.PickingInfo) {
  28540. return null;
  28541. }
  28542. var pickingInfo = null;
  28543. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28544. var mesh = this.meshes[meshIndex];
  28545. if (predicate) {
  28546. if (!predicate(mesh)) {
  28547. continue;
  28548. }
  28549. }
  28550. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28551. continue;
  28552. }
  28553. var world = mesh.getWorldMatrix();
  28554. var ray = rayFunction(world);
  28555. var result = mesh.intersects(ray, fastCheck);
  28556. if (!result || !result.hit)
  28557. continue;
  28558. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28559. continue;
  28560. pickingInfo = result;
  28561. if (fastCheck) {
  28562. break;
  28563. }
  28564. }
  28565. return pickingInfo || new BABYLON.PickingInfo();
  28566. };
  28567. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28568. if (!BABYLON.PickingInfo) {
  28569. return null;
  28570. }
  28571. var pickingInfos = new Array();
  28572. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28573. var mesh = this.meshes[meshIndex];
  28574. if (predicate) {
  28575. if (!predicate(mesh)) {
  28576. continue;
  28577. }
  28578. }
  28579. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28580. continue;
  28581. }
  28582. var world = mesh.getWorldMatrix();
  28583. var ray = rayFunction(world);
  28584. var result = mesh.intersects(ray, false);
  28585. if (!result || !result.hit)
  28586. continue;
  28587. pickingInfos.push(result);
  28588. }
  28589. return pickingInfos;
  28590. };
  28591. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28592. if (!BABYLON.PickingInfo) {
  28593. return null;
  28594. }
  28595. var pickingInfo = null;
  28596. if (!camera) {
  28597. if (!this.activeCamera) {
  28598. return null;
  28599. }
  28600. camera = this.activeCamera;
  28601. }
  28602. if (this.spriteManagers.length > 0) {
  28603. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28604. var spriteManager = this.spriteManagers[spriteIndex];
  28605. if (!spriteManager.isPickable) {
  28606. continue;
  28607. }
  28608. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28609. if (!result || !result.hit)
  28610. continue;
  28611. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28612. continue;
  28613. pickingInfo = result;
  28614. if (fastCheck) {
  28615. break;
  28616. }
  28617. }
  28618. }
  28619. return pickingInfo || new BABYLON.PickingInfo();
  28620. };
  28621. /** Launch a ray to try to pick a mesh in the scene
  28622. * @param x position on screen
  28623. * @param y position on screen
  28624. * @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
  28625. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28626. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28627. * @returns a PickingInfo
  28628. */
  28629. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28630. var _this = this;
  28631. if (!BABYLON.PickingInfo) {
  28632. return null;
  28633. }
  28634. var result = this._internalPick(function (world) {
  28635. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28636. return _this._tempPickingRay;
  28637. }, predicate, fastCheck);
  28638. if (result) {
  28639. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28640. }
  28641. return result;
  28642. };
  28643. /** Launch a ray to try to pick a sprite in the scene
  28644. * @param x position on screen
  28645. * @param y position on screen
  28646. * @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
  28647. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28648. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28649. * @returns a PickingInfo
  28650. */
  28651. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28652. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28653. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28654. };
  28655. /** Use the given ray to pick a mesh in the scene
  28656. * @param ray The ray to use to pick meshes
  28657. * @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
  28658. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28659. * @returns a PickingInfo
  28660. */
  28661. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28662. var _this = this;
  28663. var result = this._internalPick(function (world) {
  28664. if (!_this._pickWithRayInverseMatrix) {
  28665. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28666. }
  28667. world.invertToRef(_this._pickWithRayInverseMatrix);
  28668. if (!_this._cachedRayForTransform) {
  28669. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28670. }
  28671. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28672. return _this._cachedRayForTransform;
  28673. }, predicate, fastCheck);
  28674. if (result) {
  28675. result.ray = ray;
  28676. }
  28677. return result;
  28678. };
  28679. /**
  28680. * Launch a ray to try to pick a mesh in the scene
  28681. * @param x X position on screen
  28682. * @param y Y position on screen
  28683. * @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
  28684. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28685. * @returns an array of PickingInfo
  28686. */
  28687. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28688. var _this = this;
  28689. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28690. };
  28691. /**
  28692. * Launch a ray to try to pick a mesh in the scene
  28693. * @param ray Ray to use
  28694. * @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
  28695. * @returns an array of PickingInfo
  28696. */
  28697. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28698. var _this = this;
  28699. return this._internalMultiPick(function (world) {
  28700. if (!_this._pickWithRayInverseMatrix) {
  28701. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28702. }
  28703. world.invertToRef(_this._pickWithRayInverseMatrix);
  28704. if (!_this._cachedRayForTransform) {
  28705. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28706. }
  28707. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28708. return _this._cachedRayForTransform;
  28709. }, predicate);
  28710. };
  28711. /**
  28712. * Force the value of meshUnderPointer
  28713. * @param mesh defines the mesh to use
  28714. */
  28715. Scene.prototype.setPointerOverMesh = function (mesh) {
  28716. if (this._pointerOverMesh === mesh) {
  28717. return;
  28718. }
  28719. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28720. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28721. }
  28722. this._pointerOverMesh = mesh;
  28723. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28724. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28725. }
  28726. };
  28727. /**
  28728. * Gets the mesh under the pointer
  28729. * @returns a Mesh or null if no mesh is under the pointer
  28730. */
  28731. Scene.prototype.getPointerOverMesh = function () {
  28732. return this._pointerOverMesh;
  28733. };
  28734. /**
  28735. * Force the sprite under the pointer
  28736. * @param sprite defines the sprite to use
  28737. */
  28738. Scene.prototype.setPointerOverSprite = function (sprite) {
  28739. if (this._pointerOverSprite === sprite) {
  28740. return;
  28741. }
  28742. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28743. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28744. }
  28745. this._pointerOverSprite = sprite;
  28746. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28747. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28748. }
  28749. };
  28750. /**
  28751. * Gets the sprite under the pointer
  28752. * @returns a Sprite or null if no sprite is under the pointer
  28753. */
  28754. Scene.prototype.getPointerOverSprite = function () {
  28755. return this._pointerOverSprite;
  28756. };
  28757. // Physics
  28758. /**
  28759. * Gets the current physics engine
  28760. * @returns a PhysicsEngine or null if none attached
  28761. */
  28762. Scene.prototype.getPhysicsEngine = function () {
  28763. return this._physicsEngine;
  28764. };
  28765. /**
  28766. * Enables physics to the current scene
  28767. * @param gravity defines the scene's gravity for the physics engine
  28768. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28769. * @return a boolean indicating if the physics engine was initialized
  28770. */
  28771. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28772. if (gravity === void 0) { gravity = null; }
  28773. if (this._physicsEngine) {
  28774. return true;
  28775. }
  28776. try {
  28777. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28778. return true;
  28779. }
  28780. catch (e) {
  28781. BABYLON.Tools.Error(e.message);
  28782. return false;
  28783. }
  28784. };
  28785. /**
  28786. * Disables and disposes the physics engine associated with the scene
  28787. */
  28788. Scene.prototype.disablePhysicsEngine = function () {
  28789. if (!this._physicsEngine) {
  28790. return;
  28791. }
  28792. this._physicsEngine.dispose();
  28793. this._physicsEngine = null;
  28794. };
  28795. /**
  28796. * Gets a boolean indicating if there is an active physics engine
  28797. * @returns a boolean indicating if there is an active physics engine
  28798. */
  28799. Scene.prototype.isPhysicsEnabled = function () {
  28800. return this._physicsEngine !== undefined;
  28801. };
  28802. /**
  28803. * Deletes a physics compound impostor
  28804. * @param compound defines the compound to delete
  28805. */
  28806. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28807. var mesh = compound.parts[0].mesh;
  28808. if (mesh.physicsImpostor) {
  28809. mesh.physicsImpostor.dispose( /*true*/);
  28810. mesh.physicsImpostor = null;
  28811. }
  28812. };
  28813. // Misc.
  28814. /** @hidden */
  28815. Scene.prototype._rebuildGeometries = function () {
  28816. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28817. var geometry = _a[_i];
  28818. geometry._rebuild();
  28819. }
  28820. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28821. var mesh = _c[_b];
  28822. mesh._rebuild();
  28823. }
  28824. if (this.postProcessManager) {
  28825. this.postProcessManager._rebuild();
  28826. }
  28827. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28828. var layer = _e[_d];
  28829. layer._rebuild();
  28830. }
  28831. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28832. var effectLayer = _g[_f];
  28833. effectLayer._rebuild();
  28834. }
  28835. if (this._boundingBoxRenderer) {
  28836. this._boundingBoxRenderer._rebuild();
  28837. }
  28838. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28839. var system = _j[_h];
  28840. system.rebuild();
  28841. }
  28842. if (this._postProcessRenderPipelineManager) {
  28843. this._postProcessRenderPipelineManager._rebuild();
  28844. }
  28845. };
  28846. /** @hidden */
  28847. Scene.prototype._rebuildTextures = function () {
  28848. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28849. var texture = _a[_i];
  28850. texture._rebuild();
  28851. }
  28852. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28853. };
  28854. /**
  28855. * Creates a default light for the scene.
  28856. * @param replace Whether to replace the existing lights in the scene.
  28857. */
  28858. Scene.prototype.createDefaultLight = function (replace) {
  28859. if (replace === void 0) { replace = false; }
  28860. // Dispose existing light in replace mode.
  28861. if (replace) {
  28862. if (this.lights) {
  28863. for (var i = 0; i < this.lights.length; i++) {
  28864. this.lights[i].dispose();
  28865. }
  28866. }
  28867. }
  28868. // Light
  28869. if (this.lights.length === 0) {
  28870. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28871. }
  28872. };
  28873. /**
  28874. * Creates a default camera for the scene.
  28875. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28876. * @param replace Whether to replace the existing active camera in the scene.
  28877. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28878. */
  28879. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28880. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28881. if (replace === void 0) { replace = false; }
  28882. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28883. // Dispose existing camera in replace mode.
  28884. if (replace) {
  28885. if (this.activeCamera) {
  28886. this.activeCamera.dispose();
  28887. this.activeCamera = null;
  28888. }
  28889. }
  28890. // Camera
  28891. if (!this.activeCamera) {
  28892. var worldExtends = this.getWorldExtends();
  28893. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28894. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28895. var camera;
  28896. var radius = worldSize.length() * 1.5;
  28897. // empty scene scenario!
  28898. if (!isFinite(radius)) {
  28899. radius = 1;
  28900. worldCenter.copyFromFloats(0, 0, 0);
  28901. }
  28902. if (createArcRotateCamera) {
  28903. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28904. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28905. arcRotateCamera.wheelPrecision = 100 / radius;
  28906. camera = arcRotateCamera;
  28907. }
  28908. else {
  28909. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28910. freeCamera.setTarget(worldCenter);
  28911. camera = freeCamera;
  28912. }
  28913. camera.minZ = radius * 0.01;
  28914. camera.maxZ = radius * 1000;
  28915. camera.speed = radius * 0.2;
  28916. this.activeCamera = camera;
  28917. var canvas = this.getEngine().getRenderingCanvas();
  28918. if (attachCameraControls && canvas) {
  28919. camera.attachControl(canvas);
  28920. }
  28921. }
  28922. };
  28923. /**
  28924. * Creates a default camera and a default light
  28925. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28926. * @param replace defines if the camera and/or light will replace the existing ones
  28927. * @param attachCameraControls defines if attachControl will be called on the new camera
  28928. */
  28929. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28930. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28931. if (replace === void 0) { replace = false; }
  28932. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28933. this.createDefaultLight(replace);
  28934. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28935. };
  28936. /**
  28937. * Creates a new sky box
  28938. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28939. * @param environmentTexture defines the texture to use as environment texture
  28940. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28941. * @param scale defines the overall scale of the skybox
  28942. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28943. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28944. * @returns a new mesh holding the sky box
  28945. */
  28946. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28947. if (pbr === void 0) { pbr = false; }
  28948. if (scale === void 0) { scale = 1000; }
  28949. if (blur === void 0) { blur = 0; }
  28950. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28951. if (!environmentTexture) {
  28952. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28953. return null;
  28954. }
  28955. if (setGlobalEnvTexture) {
  28956. if (environmentTexture) {
  28957. this.environmentTexture = environmentTexture;
  28958. }
  28959. }
  28960. // Skybox
  28961. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28962. if (pbr) {
  28963. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28964. hdrSkyboxMaterial.backFaceCulling = false;
  28965. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28966. if (hdrSkyboxMaterial.reflectionTexture) {
  28967. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28968. }
  28969. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28970. hdrSkyboxMaterial.disableLighting = true;
  28971. hdrSkyboxMaterial.twoSidedLighting = true;
  28972. hdrSkybox.infiniteDistance = true;
  28973. hdrSkybox.material = hdrSkyboxMaterial;
  28974. }
  28975. else {
  28976. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28977. skyboxMaterial.backFaceCulling = false;
  28978. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28979. if (skyboxMaterial.reflectionTexture) {
  28980. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28981. }
  28982. skyboxMaterial.disableLighting = true;
  28983. hdrSkybox.infiniteDistance = true;
  28984. hdrSkybox.material = skyboxMaterial;
  28985. }
  28986. return hdrSkybox;
  28987. };
  28988. /**
  28989. * Creates a new environment
  28990. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28991. * @param options defines the options you can use to configure the environment
  28992. * @returns the new EnvironmentHelper
  28993. */
  28994. Scene.prototype.createDefaultEnvironment = function (options) {
  28995. if (BABYLON.EnvironmentHelper) {
  28996. return new BABYLON.EnvironmentHelper(options, this);
  28997. }
  28998. return null;
  28999. };
  29000. /**
  29001. * Creates a new VREXperienceHelper
  29002. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29003. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29004. * @returns a new VREXperienceHelper
  29005. */
  29006. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29007. if (webVROptions === void 0) { webVROptions = {}; }
  29008. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29009. };
  29010. // Tags
  29011. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29012. if (tagsQuery === undefined) {
  29013. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29014. return list;
  29015. }
  29016. var listByTags = [];
  29017. forEach = forEach || (function (item) { return; });
  29018. for (var i in list) {
  29019. var item = list[i];
  29020. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29021. listByTags.push(item);
  29022. forEach(item);
  29023. }
  29024. }
  29025. return listByTags;
  29026. };
  29027. /**
  29028. * Get a list of meshes by tags
  29029. * @param tagsQuery defines the tags query to use
  29030. * @param forEach defines a predicate used to filter results
  29031. * @returns an array of Mesh
  29032. */
  29033. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29034. return this._getByTags(this.meshes, tagsQuery, forEach);
  29035. };
  29036. /**
  29037. * Get a list of cameras by tags
  29038. * @param tagsQuery defines the tags query to use
  29039. * @param forEach defines a predicate used to filter results
  29040. * @returns an array of Camera
  29041. */
  29042. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29043. return this._getByTags(this.cameras, tagsQuery, forEach);
  29044. };
  29045. /**
  29046. * Get a list of lights by tags
  29047. * @param tagsQuery defines the tags query to use
  29048. * @param forEach defines a predicate used to filter results
  29049. * @returns an array of Light
  29050. */
  29051. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29052. return this._getByTags(this.lights, tagsQuery, forEach);
  29053. };
  29054. /**
  29055. * Get a list of materials by tags
  29056. * @param tagsQuery defines the tags query to use
  29057. * @param forEach defines a predicate used to filter results
  29058. * @returns an array of Material
  29059. */
  29060. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29061. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29062. };
  29063. /**
  29064. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29065. * This allowed control for front to back rendering or reversly depending of the special needs.
  29066. *
  29067. * @param renderingGroupId The rendering group id corresponding to its index
  29068. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29069. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29070. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29071. */
  29072. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29073. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29074. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29075. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29076. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29077. };
  29078. /**
  29079. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29080. *
  29081. * @param renderingGroupId The rendering group id corresponding to its index
  29082. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29083. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29084. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29085. */
  29086. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29087. if (depth === void 0) { depth = true; }
  29088. if (stencil === void 0) { stencil = true; }
  29089. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29090. };
  29091. /**
  29092. * Will flag all materials as dirty to trigger new shader compilation
  29093. * @param flag defines the flag used to specify which material part must be marked as dirty
  29094. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29095. */
  29096. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29097. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29098. var material = _a[_i];
  29099. if (predicate && !predicate(material)) {
  29100. continue;
  29101. }
  29102. material.markAsDirty(flag);
  29103. }
  29104. };
  29105. /** @hidden */
  29106. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29107. var _this = this;
  29108. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29109. this._activeRequests.push(request);
  29110. request.onCompleteObservable.add(function (request) {
  29111. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29112. });
  29113. return request;
  29114. };
  29115. /** @hidden */
  29116. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29117. var _this = this;
  29118. return new Promise(function (resolve, reject) {
  29119. _this._loadFile(url, function (data) {
  29120. resolve(data);
  29121. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29122. reject(exception);
  29123. });
  29124. });
  29125. };
  29126. // Statics
  29127. Scene._FOGMODE_NONE = 0;
  29128. Scene._FOGMODE_EXP = 1;
  29129. Scene._FOGMODE_EXP2 = 2;
  29130. Scene._FOGMODE_LINEAR = 3;
  29131. Scene._uniqueIdCounter = 0;
  29132. /**
  29133. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29134. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29135. */
  29136. Scene.MinDeltaTime = 1.0;
  29137. /**
  29138. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29139. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29140. */
  29141. Scene.MaxDeltaTime = 1000.0;
  29142. /** The distance in pixel that you have to move to prevent some events */
  29143. Scene.DragMovementThreshold = 10; // in pixels
  29144. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29145. Scene.LongPressDelay = 500; // in milliseconds
  29146. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29147. Scene.DoubleClickDelay = 300; // in milliseconds
  29148. /** If you need to check double click without raising a single click at first click, enable this flag */
  29149. Scene.ExclusiveDoubleClickMode = false;
  29150. return Scene;
  29151. }());
  29152. BABYLON.Scene = Scene;
  29153. })(BABYLON || (BABYLON = {}));
  29154. //# sourceMappingURL=babylon.scene.js.map
  29155. var BABYLON;
  29156. (function (BABYLON) {
  29157. /**
  29158. * Set of assets to keep when moving a scene into an asset container.
  29159. */
  29160. var KeepAssets = /** @class */ (function () {
  29161. function KeepAssets() {
  29162. /**
  29163. * Cameras to keep.
  29164. */
  29165. this.cameras = new Array();
  29166. /**
  29167. * Lights to keep.
  29168. */
  29169. this.lights = new Array();
  29170. /**
  29171. * Meshes to keep.
  29172. */
  29173. this.meshes = new Array();
  29174. /**
  29175. * Skeletons to keep.
  29176. */
  29177. this.skeletons = new Array();
  29178. /**
  29179. * ParticleSystems to keep.
  29180. */
  29181. this.particleSystems = new Array();
  29182. /**
  29183. * Animations to keep.
  29184. */
  29185. this.animations = new Array();
  29186. /**
  29187. * AnimationGroups to keep.
  29188. */
  29189. this.animationGroups = new Array();
  29190. /**
  29191. * MultiMaterials to keep.
  29192. */
  29193. this.multiMaterials = new Array();
  29194. /**
  29195. * Materials to keep.
  29196. */
  29197. this.materials = new Array();
  29198. /**
  29199. * MorphTargetManagers to keep.
  29200. */
  29201. this.morphTargetManagers = new Array();
  29202. /**
  29203. * Geometries to keep.
  29204. */
  29205. this.geometries = new Array();
  29206. /**
  29207. * TransformNodes to keep.
  29208. */
  29209. this.transformNodes = new Array();
  29210. /**
  29211. * LensFlareSystems to keep.
  29212. */
  29213. this.lensFlareSystems = new Array();
  29214. /**
  29215. * ShadowGenerators to keep.
  29216. */
  29217. this.shadowGenerators = new Array();
  29218. /**
  29219. * ActionManagers to keep.
  29220. */
  29221. this.actionManagers = new Array();
  29222. /**
  29223. * Sounds to keep.
  29224. */
  29225. this.sounds = new Array();
  29226. /**
  29227. * Textures to keep.
  29228. */
  29229. this.textures = new Array();
  29230. /**
  29231. * Effect layers to keep.
  29232. */
  29233. this.effectLayers = new Array();
  29234. }
  29235. return KeepAssets;
  29236. }());
  29237. BABYLON.KeepAssets = KeepAssets;
  29238. /**
  29239. * Container with a set of assets that can be added or removed from a scene.
  29240. */
  29241. var AssetContainer = /** @class */ (function () {
  29242. /**
  29243. * Instantiates an AssetContainer.
  29244. * @param scene The scene the AssetContainer belongs to.
  29245. */
  29246. function AssetContainer(scene) {
  29247. // Objects
  29248. /**
  29249. * Cameras populated in the container.
  29250. */
  29251. this.cameras = new Array();
  29252. /**
  29253. * Lights populated in the container.
  29254. */
  29255. this.lights = new Array();
  29256. /**
  29257. * Meshes populated in the container.
  29258. */
  29259. this.meshes = new Array();
  29260. /**
  29261. * Skeletons populated in the container.
  29262. */
  29263. this.skeletons = new Array();
  29264. /**
  29265. * ParticleSystems populated in the container.
  29266. */
  29267. this.particleSystems = new Array();
  29268. /**
  29269. * Animations populated in the container.
  29270. */
  29271. this.animations = new Array();
  29272. /**
  29273. * AnimationGroups populated in the container.
  29274. */
  29275. this.animationGroups = new Array();
  29276. /**
  29277. * MultiMaterials populated in the container.
  29278. */
  29279. this.multiMaterials = new Array();
  29280. /**
  29281. * Materials populated in the container.
  29282. */
  29283. this.materials = new Array();
  29284. /**
  29285. * MorphTargetManagers populated in the container.
  29286. */
  29287. this.morphTargetManagers = new Array();
  29288. /**
  29289. * Geometries populated in the container.
  29290. */
  29291. this.geometries = new Array();
  29292. /**
  29293. * TransformNodes populated in the container.
  29294. */
  29295. this.transformNodes = new Array();
  29296. /**
  29297. * LensFlareSystems populated in the container.
  29298. */
  29299. this.lensFlareSystems = new Array();
  29300. /**
  29301. * ShadowGenerators populated in the container.
  29302. */
  29303. this.shadowGenerators = new Array();
  29304. /**
  29305. * ActionManagers populated in the container.
  29306. */
  29307. this.actionManagers = new Array();
  29308. /**
  29309. * Sounds populated in the container.
  29310. */
  29311. this.sounds = new Array();
  29312. /**
  29313. * Textures populated in the container.
  29314. */
  29315. this.textures = new Array();
  29316. /**
  29317. * Effect layers populated in the container.
  29318. */
  29319. this.effectLayers = new Array();
  29320. this.scene = scene;
  29321. }
  29322. /**
  29323. * Adds all the assets from the container to the scene.
  29324. */
  29325. AssetContainer.prototype.addAllToScene = function () {
  29326. var _this = this;
  29327. this.cameras.forEach(function (o) {
  29328. _this.scene.addCamera(o);
  29329. });
  29330. this.lights.forEach(function (o) {
  29331. _this.scene.addLight(o);
  29332. });
  29333. this.meshes.forEach(function (o) {
  29334. _this.scene.addMesh(o);
  29335. });
  29336. this.skeletons.forEach(function (o) {
  29337. _this.scene.addSkeleton(o);
  29338. });
  29339. this.particleSystems.forEach(function (o) {
  29340. _this.scene.addParticleSystem(o);
  29341. });
  29342. this.animations.forEach(function (o) {
  29343. _this.scene.addAnimation(o);
  29344. });
  29345. this.animationGroups.forEach(function (o) {
  29346. _this.scene.addAnimationGroup(o);
  29347. });
  29348. this.multiMaterials.forEach(function (o) {
  29349. _this.scene.addMultiMaterial(o);
  29350. });
  29351. this.materials.forEach(function (o) {
  29352. _this.scene.addMaterial(o);
  29353. });
  29354. this.morphTargetManagers.forEach(function (o) {
  29355. _this.scene.addMorphTargetManager(o);
  29356. });
  29357. this.geometries.forEach(function (o) {
  29358. _this.scene.addGeometry(o);
  29359. });
  29360. this.transformNodes.forEach(function (o) {
  29361. _this.scene.addTransformNode(o);
  29362. });
  29363. this.lensFlareSystems.forEach(function (o) {
  29364. _this.scene.addLensFlareSystem(o);
  29365. });
  29366. this.actionManagers.forEach(function (o) {
  29367. _this.scene.addActionManager(o);
  29368. });
  29369. this.sounds.forEach(function (o) {
  29370. o.play();
  29371. o.autoplay = true;
  29372. _this.scene.mainSoundTrack.AddSound(o);
  29373. });
  29374. this.textures.forEach(function (o) {
  29375. _this.scene.addTexture(o);
  29376. });
  29377. this.effectLayers.forEach(function (o) {
  29378. _this.scene.addEffectLayer(o);
  29379. });
  29380. };
  29381. /**
  29382. * Removes all the assets in the container from the scene
  29383. */
  29384. AssetContainer.prototype.removeAllFromScene = function () {
  29385. var _this = this;
  29386. this.cameras.forEach(function (o) {
  29387. _this.scene.removeCamera(o);
  29388. });
  29389. this.lights.forEach(function (o) {
  29390. _this.scene.removeLight(o);
  29391. });
  29392. this.meshes.forEach(function (o) {
  29393. _this.scene.removeMesh(o);
  29394. });
  29395. this.skeletons.forEach(function (o) {
  29396. _this.scene.removeSkeleton(o);
  29397. });
  29398. this.particleSystems.forEach(function (o) {
  29399. _this.scene.removeParticleSystem(o);
  29400. });
  29401. this.animations.forEach(function (o) {
  29402. _this.scene.removeAnimation(o);
  29403. });
  29404. this.animationGroups.forEach(function (o) {
  29405. _this.scene.removeAnimationGroup(o);
  29406. });
  29407. this.multiMaterials.forEach(function (o) {
  29408. _this.scene.removeMultiMaterial(o);
  29409. });
  29410. this.materials.forEach(function (o) {
  29411. _this.scene.removeMaterial(o);
  29412. });
  29413. this.morphTargetManagers.forEach(function (o) {
  29414. _this.scene.removeMorphTargetManager(o);
  29415. });
  29416. this.geometries.forEach(function (o) {
  29417. _this.scene.removeGeometry(o);
  29418. });
  29419. this.transformNodes.forEach(function (o) {
  29420. _this.scene.removeTransformNode(o);
  29421. });
  29422. this.lensFlareSystems.forEach(function (o) {
  29423. _this.scene.removeLensFlareSystem(o);
  29424. });
  29425. this.actionManagers.forEach(function (o) {
  29426. _this.scene.removeActionManager(o);
  29427. });
  29428. this.sounds.forEach(function (o) {
  29429. o.stop();
  29430. o.autoplay = false;
  29431. _this.scene.mainSoundTrack.RemoveSound(o);
  29432. });
  29433. this.textures.forEach(function (o) {
  29434. _this.scene.removeTexture(o);
  29435. });
  29436. this.effectLayers.forEach(function (o) {
  29437. _this.scene.removeEffectLayer(o);
  29438. });
  29439. };
  29440. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29441. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29442. var asset = sourceAssets_1[_i];
  29443. var move = true;
  29444. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29445. var keepAsset = keepAssets_1[_a];
  29446. if (asset === keepAsset) {
  29447. move = false;
  29448. break;
  29449. }
  29450. }
  29451. if (move) {
  29452. targetAssets.push(asset);
  29453. }
  29454. }
  29455. };
  29456. /**
  29457. * Removes all the assets contained in the scene and adds them to the container.
  29458. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29459. */
  29460. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29461. if (keepAssets === undefined) {
  29462. keepAssets = new KeepAssets();
  29463. }
  29464. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29465. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29466. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29467. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29468. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29469. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29470. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29471. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29472. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29473. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29474. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29475. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29476. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29477. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29478. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29479. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29480. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29481. this.removeAllFromScene();
  29482. };
  29483. /**
  29484. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29485. * @returns the root mesh
  29486. */
  29487. AssetContainer.prototype.createRootMesh = function () {
  29488. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29489. this.meshes.forEach(function (m) {
  29490. if (!m.parent) {
  29491. rootMesh.addChild(m);
  29492. }
  29493. });
  29494. this.meshes.unshift(rootMesh);
  29495. return rootMesh;
  29496. };
  29497. return AssetContainer;
  29498. }());
  29499. BABYLON.AssetContainer = AssetContainer;
  29500. })(BABYLON || (BABYLON = {}));
  29501. //# sourceMappingURL=babylon.assetContainer.js.map
  29502. var BABYLON;
  29503. (function (BABYLON) {
  29504. var Buffer = /** @class */ (function () {
  29505. /**
  29506. * Constructor
  29507. * @param engine the engine
  29508. * @param data the data to use for this buffer
  29509. * @param updatable whether the data is updatable
  29510. * @param stride the stride (optional)
  29511. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29512. * @param instanced whether the buffer is instanced (optional)
  29513. * @param useBytes set to true if the stride in in bytes (optional)
  29514. */
  29515. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29516. if (stride === void 0) { stride = 0; }
  29517. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29518. if (instanced === void 0) { instanced = false; }
  29519. if (useBytes === void 0) { useBytes = false; }
  29520. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29521. this._engine = engine.getScene().getEngine();
  29522. }
  29523. else {
  29524. this._engine = engine;
  29525. }
  29526. this._updatable = updatable;
  29527. this._instanced = instanced;
  29528. this._data = data;
  29529. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29530. if (!postponeInternalCreation) { // by default
  29531. this.create();
  29532. }
  29533. }
  29534. /**
  29535. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29536. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29537. * @param offset defines offset in the buffer (0 by default)
  29538. * @param size defines the size in floats of attributes (position is 3 for instance)
  29539. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29540. * @param instanced defines if the vertex buffer contains indexed data
  29541. * @param useBytes defines if the offset and stride are in bytes
  29542. * @returns the new vertex buffer
  29543. */
  29544. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29545. if (useBytes === void 0) { useBytes = false; }
  29546. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29547. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29548. // a lot of these parameters are ignored as they are overriden by the buffer
  29549. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29550. };
  29551. // Properties
  29552. Buffer.prototype.isUpdatable = function () {
  29553. return this._updatable;
  29554. };
  29555. Buffer.prototype.getData = function () {
  29556. return this._data;
  29557. };
  29558. Buffer.prototype.getBuffer = function () {
  29559. return this._buffer;
  29560. };
  29561. /**
  29562. * Gets the stride in float32 units (i.e. byte stride / 4).
  29563. * May not be an integer if the byte stride is not divisible by 4.
  29564. * DEPRECATED. Use byteStride instead.
  29565. * @returns the stride in float32 units
  29566. */
  29567. Buffer.prototype.getStrideSize = function () {
  29568. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29569. };
  29570. // Methods
  29571. Buffer.prototype.create = function (data) {
  29572. if (data === void 0) { data = null; }
  29573. if (!data && this._buffer) {
  29574. return; // nothing to do
  29575. }
  29576. data = data || this._data;
  29577. if (!data) {
  29578. return;
  29579. }
  29580. if (!this._buffer) { // create buffer
  29581. if (this._updatable) {
  29582. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29583. this._data = data;
  29584. }
  29585. else {
  29586. this._buffer = this._engine.createVertexBuffer(data);
  29587. }
  29588. }
  29589. else if (this._updatable) { // update buffer
  29590. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29591. this._data = data;
  29592. }
  29593. };
  29594. Buffer.prototype._rebuild = function () {
  29595. this._buffer = null;
  29596. this.create(this._data);
  29597. };
  29598. Buffer.prototype.update = function (data) {
  29599. this.create(data);
  29600. };
  29601. /**
  29602. * Updates the data directly.
  29603. * @param data the new data
  29604. * @param offset the new offset
  29605. * @param vertexCount the vertex count (optional)
  29606. * @param useBytes set to true if the offset is in bytes
  29607. */
  29608. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29609. if (useBytes === void 0) { useBytes = false; }
  29610. if (!this._buffer) {
  29611. return;
  29612. }
  29613. if (this._updatable) { // update buffer
  29614. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29615. this._data = null;
  29616. }
  29617. };
  29618. Buffer.prototype.dispose = function () {
  29619. if (!this._buffer) {
  29620. return;
  29621. }
  29622. if (this._engine._releaseBuffer(this._buffer)) {
  29623. this._buffer = null;
  29624. }
  29625. };
  29626. return Buffer;
  29627. }());
  29628. BABYLON.Buffer = Buffer;
  29629. })(BABYLON || (BABYLON = {}));
  29630. //# sourceMappingURL=babylon.buffer.js.map
  29631. var BABYLON;
  29632. (function (BABYLON) {
  29633. var VertexBuffer = /** @class */ (function () {
  29634. /**
  29635. * Constructor
  29636. * @param engine the engine
  29637. * @param data the data to use for this vertex buffer
  29638. * @param kind the vertex buffer kind
  29639. * @param updatable whether the data is updatable
  29640. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29641. * @param stride the stride (optional)
  29642. * @param instanced whether the buffer is instanced (optional)
  29643. * @param offset the offset of the data (optional)
  29644. * @param size the number of components (optional)
  29645. * @param type the type of the component (optional)
  29646. * @param normalized whether the data contains normalized data (optional)
  29647. * @param useBytes set to true if stride and offset are in bytes (optional)
  29648. */
  29649. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29650. if (normalized === void 0) { normalized = false; }
  29651. if (useBytes === void 0) { useBytes = false; }
  29652. if (data instanceof BABYLON.Buffer) {
  29653. this._buffer = data;
  29654. this._ownsBuffer = false;
  29655. }
  29656. else {
  29657. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29658. this._ownsBuffer = true;
  29659. }
  29660. this._kind = kind;
  29661. if (type == undefined) {
  29662. var data_1 = this.getData();
  29663. this.type = VertexBuffer.FLOAT;
  29664. if (data_1 instanceof Int8Array)
  29665. this.type = VertexBuffer.BYTE;
  29666. else if (data_1 instanceof Uint8Array)
  29667. this.type = VertexBuffer.UNSIGNED_BYTE;
  29668. else if (data_1 instanceof Int16Array)
  29669. this.type = VertexBuffer.SHORT;
  29670. else if (data_1 instanceof Uint16Array)
  29671. this.type = VertexBuffer.UNSIGNED_SHORT;
  29672. else if (data_1 instanceof Int32Array)
  29673. this.type = VertexBuffer.INT;
  29674. else if (data_1 instanceof Uint32Array)
  29675. this.type = VertexBuffer.UNSIGNED_INT;
  29676. }
  29677. else {
  29678. this.type = type;
  29679. }
  29680. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29681. if (useBytes) {
  29682. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29683. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29684. this.byteOffset = offset || 0;
  29685. }
  29686. else {
  29687. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29688. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29689. this.byteOffset = (offset || 0) * typeByteLength;
  29690. }
  29691. this.normalized = normalized;
  29692. this._instanced = instanced !== undefined ? instanced : false;
  29693. this._instanceDivisor = instanced ? 1 : 0;
  29694. }
  29695. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29696. /**
  29697. * Gets or sets the instance divisor when in instanced mode
  29698. */
  29699. get: function () {
  29700. return this._instanceDivisor;
  29701. },
  29702. set: function (value) {
  29703. this._instanceDivisor = value;
  29704. if (value == 0) {
  29705. this._instanced = false;
  29706. }
  29707. else {
  29708. this._instanced = true;
  29709. }
  29710. },
  29711. enumerable: true,
  29712. configurable: true
  29713. });
  29714. VertexBuffer.prototype._rebuild = function () {
  29715. if (!this._buffer) {
  29716. return;
  29717. }
  29718. this._buffer._rebuild();
  29719. };
  29720. /**
  29721. * Returns the kind of the VertexBuffer (string).
  29722. */
  29723. VertexBuffer.prototype.getKind = function () {
  29724. return this._kind;
  29725. };
  29726. // Properties
  29727. /**
  29728. * Boolean : is the VertexBuffer updatable ?
  29729. */
  29730. VertexBuffer.prototype.isUpdatable = function () {
  29731. return this._buffer.isUpdatable();
  29732. };
  29733. /**
  29734. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29735. */
  29736. VertexBuffer.prototype.getData = function () {
  29737. return this._buffer.getData();
  29738. };
  29739. /**
  29740. * Returns the WebGLBuffer associated to the VertexBuffer.
  29741. */
  29742. VertexBuffer.prototype.getBuffer = function () {
  29743. return this._buffer.getBuffer();
  29744. };
  29745. /**
  29746. * Returns the stride as a multiple of the type byte length.
  29747. * DEPRECATED. Use byteStride instead.
  29748. */
  29749. VertexBuffer.prototype.getStrideSize = function () {
  29750. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29751. };
  29752. /**
  29753. * Returns the offset as a multiple of the type byte length.
  29754. * DEPRECATED. Use byteOffset instead.
  29755. */
  29756. VertexBuffer.prototype.getOffset = function () {
  29757. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29758. };
  29759. /**
  29760. * Returns the number of components per vertex attribute (integer).
  29761. */
  29762. VertexBuffer.prototype.getSize = function () {
  29763. return this._size;
  29764. };
  29765. /**
  29766. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29767. */
  29768. VertexBuffer.prototype.getIsInstanced = function () {
  29769. return this._instanced;
  29770. };
  29771. /**
  29772. * Returns the instancing divisor, zero for non-instanced (integer).
  29773. */
  29774. VertexBuffer.prototype.getInstanceDivisor = function () {
  29775. return this._instanceDivisor;
  29776. };
  29777. // Methods
  29778. /**
  29779. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29780. * Returns the created WebGLBuffer.
  29781. */
  29782. VertexBuffer.prototype.create = function (data) {
  29783. return this._buffer.create(data);
  29784. };
  29785. /**
  29786. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29787. * This function will create a new buffer if the current one is not updatable
  29788. * Returns the updated WebGLBuffer.
  29789. */
  29790. VertexBuffer.prototype.update = function (data) {
  29791. return this._buffer.update(data);
  29792. };
  29793. /**
  29794. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29795. * Returns the directly updated WebGLBuffer.
  29796. * @param data the new data
  29797. * @param offset the new offset
  29798. * @param useBytes set to true if the offset is in bytes
  29799. */
  29800. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29801. if (useBytes === void 0) { useBytes = false; }
  29802. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29803. };
  29804. /**
  29805. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29806. */
  29807. VertexBuffer.prototype.dispose = function () {
  29808. if (this._ownsBuffer) {
  29809. this._buffer.dispose();
  29810. }
  29811. };
  29812. /**
  29813. * Enumerates each value of this vertex buffer as numbers.
  29814. * @param count the number of values to enumerate
  29815. * @param callback the callback function called for each value
  29816. */
  29817. VertexBuffer.prototype.forEach = function (count, callback) {
  29818. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29819. };
  29820. Object.defineProperty(VertexBuffer, "PositionKind", {
  29821. get: function () {
  29822. return VertexBuffer._PositionKind;
  29823. },
  29824. enumerable: true,
  29825. configurable: true
  29826. });
  29827. Object.defineProperty(VertexBuffer, "NormalKind", {
  29828. get: function () {
  29829. return VertexBuffer._NormalKind;
  29830. },
  29831. enumerable: true,
  29832. configurable: true
  29833. });
  29834. Object.defineProperty(VertexBuffer, "TangentKind", {
  29835. get: function () {
  29836. return VertexBuffer._TangentKind;
  29837. },
  29838. enumerable: true,
  29839. configurable: true
  29840. });
  29841. Object.defineProperty(VertexBuffer, "UVKind", {
  29842. get: function () {
  29843. return VertexBuffer._UVKind;
  29844. },
  29845. enumerable: true,
  29846. configurable: true
  29847. });
  29848. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29849. get: function () {
  29850. return VertexBuffer._UV2Kind;
  29851. },
  29852. enumerable: true,
  29853. configurable: true
  29854. });
  29855. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29856. get: function () {
  29857. return VertexBuffer._UV3Kind;
  29858. },
  29859. enumerable: true,
  29860. configurable: true
  29861. });
  29862. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29863. get: function () {
  29864. return VertexBuffer._UV4Kind;
  29865. },
  29866. enumerable: true,
  29867. configurable: true
  29868. });
  29869. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29870. get: function () {
  29871. return VertexBuffer._UV5Kind;
  29872. },
  29873. enumerable: true,
  29874. configurable: true
  29875. });
  29876. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29877. get: function () {
  29878. return VertexBuffer._UV6Kind;
  29879. },
  29880. enumerable: true,
  29881. configurable: true
  29882. });
  29883. Object.defineProperty(VertexBuffer, "ColorKind", {
  29884. get: function () {
  29885. return VertexBuffer._ColorKind;
  29886. },
  29887. enumerable: true,
  29888. configurable: true
  29889. });
  29890. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29891. get: function () {
  29892. return VertexBuffer._MatricesIndicesKind;
  29893. },
  29894. enumerable: true,
  29895. configurable: true
  29896. });
  29897. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29898. get: function () {
  29899. return VertexBuffer._MatricesWeightsKind;
  29900. },
  29901. enumerable: true,
  29902. configurable: true
  29903. });
  29904. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29905. get: function () {
  29906. return VertexBuffer._MatricesIndicesExtraKind;
  29907. },
  29908. enumerable: true,
  29909. configurable: true
  29910. });
  29911. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29912. get: function () {
  29913. return VertexBuffer._MatricesWeightsExtraKind;
  29914. },
  29915. enumerable: true,
  29916. configurable: true
  29917. });
  29918. /**
  29919. * Deduces the stride given a kind.
  29920. * @param kind The kind string to deduce
  29921. * @returns The deduced stride
  29922. */
  29923. VertexBuffer.DeduceStride = function (kind) {
  29924. switch (kind) {
  29925. case VertexBuffer.UVKind:
  29926. case VertexBuffer.UV2Kind:
  29927. case VertexBuffer.UV3Kind:
  29928. case VertexBuffer.UV4Kind:
  29929. case VertexBuffer.UV5Kind:
  29930. case VertexBuffer.UV6Kind:
  29931. return 2;
  29932. case VertexBuffer.NormalKind:
  29933. case VertexBuffer.PositionKind:
  29934. return 3;
  29935. case VertexBuffer.ColorKind:
  29936. case VertexBuffer.MatricesIndicesKind:
  29937. case VertexBuffer.MatricesIndicesExtraKind:
  29938. case VertexBuffer.MatricesWeightsKind:
  29939. case VertexBuffer.MatricesWeightsExtraKind:
  29940. case VertexBuffer.TangentKind:
  29941. return 4;
  29942. default:
  29943. throw new Error("Invalid kind '" + kind + "'");
  29944. }
  29945. };
  29946. /**
  29947. * Gets the byte length of the given type.
  29948. * @param type the type
  29949. * @returns the number of bytes
  29950. */
  29951. VertexBuffer.GetTypeByteLength = function (type) {
  29952. switch (type) {
  29953. case VertexBuffer.BYTE:
  29954. case VertexBuffer.UNSIGNED_BYTE:
  29955. return 1;
  29956. case VertexBuffer.SHORT:
  29957. case VertexBuffer.UNSIGNED_SHORT:
  29958. return 2;
  29959. case VertexBuffer.INT:
  29960. case VertexBuffer.FLOAT:
  29961. return 4;
  29962. default:
  29963. throw new Error("Invalid type '" + type + "'");
  29964. }
  29965. };
  29966. /**
  29967. * Enumerates each value of the given parameters as numbers.
  29968. * @param data the data to enumerate
  29969. * @param byteOffset the byte offset of the data
  29970. * @param byteStride the byte stride of the data
  29971. * @param componentCount the number of components per element
  29972. * @param componentType the type of the component
  29973. * @param count the total number of components
  29974. * @param normalized whether the data is normalized
  29975. * @param callback the callback function called for each value
  29976. */
  29977. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29978. if (data instanceof Array) {
  29979. var offset = byteOffset / 4;
  29980. var stride = byteStride / 4;
  29981. for (var index = 0; index < count; index += componentCount) {
  29982. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29983. callback(data[offset + componentIndex], index + componentIndex);
  29984. }
  29985. offset += stride;
  29986. }
  29987. }
  29988. else {
  29989. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29990. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29991. for (var index = 0; index < count; index += componentCount) {
  29992. var componentByteOffset = byteOffset;
  29993. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29994. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29995. callback(value, index + componentIndex);
  29996. componentByteOffset += componentByteLength;
  29997. }
  29998. byteOffset += byteStride;
  29999. }
  30000. }
  30001. };
  30002. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30003. switch (type) {
  30004. case VertexBuffer.BYTE: {
  30005. var value = dataView.getInt8(byteOffset);
  30006. if (normalized) {
  30007. value = Math.max(value / 127, -1);
  30008. }
  30009. return value;
  30010. }
  30011. case VertexBuffer.UNSIGNED_BYTE: {
  30012. var value = dataView.getUint8(byteOffset);
  30013. if (normalized) {
  30014. value = value / 255;
  30015. }
  30016. return value;
  30017. }
  30018. case VertexBuffer.SHORT: {
  30019. var value = dataView.getInt16(byteOffset, true);
  30020. if (normalized) {
  30021. value = Math.max(value / 16383, -1);
  30022. }
  30023. return value;
  30024. }
  30025. case VertexBuffer.UNSIGNED_SHORT: {
  30026. var value = dataView.getUint16(byteOffset, true);
  30027. if (normalized) {
  30028. value = value / 65535;
  30029. }
  30030. return value;
  30031. }
  30032. case VertexBuffer.FLOAT: {
  30033. return dataView.getFloat32(byteOffset, true);
  30034. }
  30035. default: {
  30036. throw new Error("Invalid component type " + type);
  30037. }
  30038. }
  30039. };
  30040. /**
  30041. * The byte type.
  30042. */
  30043. VertexBuffer.BYTE = 5120;
  30044. /**
  30045. * The unsigned byte type.
  30046. */
  30047. VertexBuffer.UNSIGNED_BYTE = 5121;
  30048. /**
  30049. * The short type.
  30050. */
  30051. VertexBuffer.SHORT = 5122;
  30052. /**
  30053. * The unsigned short type.
  30054. */
  30055. VertexBuffer.UNSIGNED_SHORT = 5123;
  30056. /**
  30057. * The integer type.
  30058. */
  30059. VertexBuffer.INT = 5124;
  30060. /**
  30061. * The unsigned integer type.
  30062. */
  30063. VertexBuffer.UNSIGNED_INT = 5125;
  30064. /**
  30065. * The float type.
  30066. */
  30067. VertexBuffer.FLOAT = 5126;
  30068. // Enums
  30069. VertexBuffer._PositionKind = "position";
  30070. VertexBuffer._NormalKind = "normal";
  30071. VertexBuffer._TangentKind = "tangent";
  30072. VertexBuffer._UVKind = "uv";
  30073. VertexBuffer._UV2Kind = "uv2";
  30074. VertexBuffer._UV3Kind = "uv3";
  30075. VertexBuffer._UV4Kind = "uv4";
  30076. VertexBuffer._UV5Kind = "uv5";
  30077. VertexBuffer._UV6Kind = "uv6";
  30078. VertexBuffer._ColorKind = "color";
  30079. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30080. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30081. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30082. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30083. return VertexBuffer;
  30084. }());
  30085. BABYLON.VertexBuffer = VertexBuffer;
  30086. })(BABYLON || (BABYLON = {}));
  30087. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30088. var BABYLON;
  30089. (function (BABYLON) {
  30090. /**
  30091. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30092. */
  30093. var DummyInternalTextureTracker = /** @class */ (function () {
  30094. function DummyInternalTextureTracker() {
  30095. /**
  30096. * Gets or set the previous tracker in the list
  30097. */
  30098. this.previous = null;
  30099. /**
  30100. * Gets or set the next tracker in the list
  30101. */
  30102. this.next = null;
  30103. }
  30104. return DummyInternalTextureTracker;
  30105. }());
  30106. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30107. })(BABYLON || (BABYLON = {}));
  30108. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30109. var BABYLON;
  30110. (function (BABYLON) {
  30111. /**
  30112. * Class used to store data associated with WebGL texture data for the engine
  30113. * This class should not be used directly
  30114. */
  30115. var InternalTexture = /** @class */ (function () {
  30116. /**
  30117. * Creates a new InternalTexture
  30118. * @param engine defines the engine to use
  30119. * @param dataSource defines the type of data that will be used
  30120. */
  30121. function InternalTexture(engine, dataSource) {
  30122. /**
  30123. * Observable called when the texture is loaded
  30124. */
  30125. this.onLoadedObservable = new BABYLON.Observable();
  30126. /**
  30127. * Gets or set the previous tracker in the list
  30128. */
  30129. this.previous = null;
  30130. /**
  30131. * Gets or set the next tracker in the list
  30132. */
  30133. this.next = null;
  30134. // Private
  30135. /** @hidden */
  30136. this._initialSlot = -1;
  30137. /** @hidden */
  30138. this._designatedSlot = -1;
  30139. /** @hidden */
  30140. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30141. /** @hidden */
  30142. this._comparisonFunction = 0;
  30143. /** @hidden */
  30144. this._isRGBD = false;
  30145. /** @hidden */
  30146. this._references = 1;
  30147. this._engine = engine;
  30148. this._dataSource = dataSource;
  30149. this._webGLTexture = engine._createTexture();
  30150. }
  30151. /**
  30152. * Gets the Engine the texture belongs to.
  30153. * @returns The babylon engine
  30154. */
  30155. InternalTexture.prototype.getEngine = function () {
  30156. return this._engine;
  30157. };
  30158. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30159. /**
  30160. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30161. */
  30162. get: function () {
  30163. return this._dataSource;
  30164. },
  30165. enumerable: true,
  30166. configurable: true
  30167. });
  30168. /**
  30169. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30170. */
  30171. InternalTexture.prototype.incrementReferences = function () {
  30172. this._references++;
  30173. };
  30174. /**
  30175. * Change the size of the texture (not the size of the content)
  30176. * @param width defines the new width
  30177. * @param height defines the new height
  30178. * @param depth defines the new depth (1 by default)
  30179. */
  30180. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30181. if (depth === void 0) { depth = 1; }
  30182. this.width = width;
  30183. this.height = height;
  30184. this.depth = depth;
  30185. this.baseWidth = width;
  30186. this.baseHeight = height;
  30187. this.baseDepth = depth;
  30188. this._size = width * height * depth;
  30189. };
  30190. /** @hidden */
  30191. InternalTexture.prototype._rebuild = function () {
  30192. var _this = this;
  30193. var proxy;
  30194. this.isReady = false;
  30195. this._cachedCoordinatesMode = null;
  30196. this._cachedWrapU = null;
  30197. this._cachedWrapV = null;
  30198. this._cachedAnisotropicFilteringLevel = null;
  30199. switch (this._dataSource) {
  30200. case InternalTexture.DATASOURCE_TEMP:
  30201. return;
  30202. case InternalTexture.DATASOURCE_URL:
  30203. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30204. _this.isReady = true;
  30205. }, null, this._buffer, undefined, this.format);
  30206. proxy._swapAndDie(this);
  30207. return;
  30208. case InternalTexture.DATASOURCE_RAW:
  30209. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30210. proxy._swapAndDie(this);
  30211. this.isReady = true;
  30212. return;
  30213. case InternalTexture.DATASOURCE_RAW3D:
  30214. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30215. proxy._swapAndDie(this);
  30216. this.isReady = true;
  30217. return;
  30218. case InternalTexture.DATASOURCE_DYNAMIC:
  30219. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30220. proxy._swapAndDie(this);
  30221. // The engine will make sure to update content so no need to flag it as isReady = true
  30222. return;
  30223. case InternalTexture.DATASOURCE_RENDERTARGET:
  30224. var options = new BABYLON.RenderTargetCreationOptions();
  30225. options.generateDepthBuffer = this._generateDepthBuffer;
  30226. options.generateMipMaps = this.generateMipMaps;
  30227. options.generateStencilBuffer = this._generateStencilBuffer;
  30228. options.samplingMode = this.samplingMode;
  30229. options.type = this.type;
  30230. if (this.isCube) {
  30231. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30232. }
  30233. else {
  30234. var size = {
  30235. width: this.width,
  30236. height: this.height
  30237. };
  30238. proxy = this._engine.createRenderTargetTexture(size, options);
  30239. }
  30240. proxy._swapAndDie(this);
  30241. this.isReady = true;
  30242. return;
  30243. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30244. var depthTextureOptions = {
  30245. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30246. comparisonFunction: this._comparisonFunction,
  30247. generateStencil: this._generateStencilBuffer,
  30248. isCube: this.isCube
  30249. };
  30250. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30251. proxy._swapAndDie(this);
  30252. this.isReady = true;
  30253. return;
  30254. case InternalTexture.DATASOURCE_CUBE:
  30255. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30256. _this.isReady = true;
  30257. }, null, this.format, this._extension);
  30258. proxy._swapAndDie(this);
  30259. return;
  30260. case InternalTexture.DATASOURCE_CUBERAW:
  30261. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30262. proxy._swapAndDie(this);
  30263. this.isReady = true;
  30264. return;
  30265. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30266. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30267. if (proxy) {
  30268. proxy._swapAndDie(_this);
  30269. }
  30270. _this.isReady = true;
  30271. }, null, this.format, this._extension);
  30272. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30273. return;
  30274. }
  30275. };
  30276. InternalTexture.prototype._swapAndDie = function (target) {
  30277. target._webGLTexture = this._webGLTexture;
  30278. if (this._framebuffer) {
  30279. target._framebuffer = this._framebuffer;
  30280. }
  30281. if (this._depthStencilBuffer) {
  30282. target._depthStencilBuffer = this._depthStencilBuffer;
  30283. }
  30284. if (this._lodTextureHigh) {
  30285. if (target._lodTextureHigh) {
  30286. target._lodTextureHigh.dispose();
  30287. }
  30288. target._lodTextureHigh = this._lodTextureHigh;
  30289. }
  30290. if (this._lodTextureMid) {
  30291. if (target._lodTextureMid) {
  30292. target._lodTextureMid.dispose();
  30293. }
  30294. target._lodTextureMid = this._lodTextureMid;
  30295. }
  30296. if (this._lodTextureLow) {
  30297. if (target._lodTextureLow) {
  30298. target._lodTextureLow.dispose();
  30299. }
  30300. target._lodTextureLow = this._lodTextureLow;
  30301. }
  30302. var cache = this._engine.getLoadedTexturesCache();
  30303. var index = cache.indexOf(this);
  30304. if (index !== -1) {
  30305. cache.splice(index, 1);
  30306. }
  30307. };
  30308. /**
  30309. * Dispose the current allocated resources
  30310. */
  30311. InternalTexture.prototype.dispose = function () {
  30312. if (!this._webGLTexture) {
  30313. return;
  30314. }
  30315. this._references--;
  30316. if (this._references === 0) {
  30317. this._engine._releaseTexture(this);
  30318. this._webGLTexture = null;
  30319. this.previous = null;
  30320. this.next = null;
  30321. }
  30322. };
  30323. /**
  30324. * The source of the texture data is unknown
  30325. */
  30326. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30327. /**
  30328. * Texture data comes from an URL
  30329. */
  30330. InternalTexture.DATASOURCE_URL = 1;
  30331. /**
  30332. * Texture data is only used for temporary storage
  30333. */
  30334. InternalTexture.DATASOURCE_TEMP = 2;
  30335. /**
  30336. * Texture data comes from raw data (ArrayBuffer)
  30337. */
  30338. InternalTexture.DATASOURCE_RAW = 3;
  30339. /**
  30340. * Texture content is dynamic (video or dynamic texture)
  30341. */
  30342. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30343. /**
  30344. * Texture content is generated by rendering to it
  30345. */
  30346. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30347. /**
  30348. * Texture content is part of a multi render target process
  30349. */
  30350. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30351. /**
  30352. * Texture data comes from a cube data file
  30353. */
  30354. InternalTexture.DATASOURCE_CUBE = 7;
  30355. /**
  30356. * Texture data comes from a raw cube data
  30357. */
  30358. InternalTexture.DATASOURCE_CUBERAW = 8;
  30359. /**
  30360. * Texture data come from a prefiltered cube data file
  30361. */
  30362. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30363. /**
  30364. * Texture content is raw 3D data
  30365. */
  30366. InternalTexture.DATASOURCE_RAW3D = 10;
  30367. /**
  30368. * Texture content is a depth texture
  30369. */
  30370. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30371. return InternalTexture;
  30372. }());
  30373. BABYLON.InternalTexture = InternalTexture;
  30374. })(BABYLON || (BABYLON = {}));
  30375. //# sourceMappingURL=babylon.internalTexture.js.map
  30376. var BABYLON;
  30377. (function (BABYLON) {
  30378. var BaseTexture = /** @class */ (function () {
  30379. function BaseTexture(scene) {
  30380. this._hasAlpha = false;
  30381. this.getAlphaFromRGB = false;
  30382. this.level = 1;
  30383. this.coordinatesIndex = 0;
  30384. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30385. /**
  30386. * | Value | Type | Description |
  30387. * | ----- | ------------------ | ----------- |
  30388. * | 0 | CLAMP_ADDRESSMODE | |
  30389. * | 1 | WRAP_ADDRESSMODE | |
  30390. * | 2 | MIRROR_ADDRESSMODE | |
  30391. */
  30392. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30393. /**
  30394. * | Value | Type | Description |
  30395. * | ----- | ------------------ | ----------- |
  30396. * | 0 | CLAMP_ADDRESSMODE | |
  30397. * | 1 | WRAP_ADDRESSMODE | |
  30398. * | 2 | MIRROR_ADDRESSMODE | |
  30399. */
  30400. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30401. /**
  30402. * | Value | Type | Description |
  30403. * | ----- | ------------------ | ----------- |
  30404. * | 0 | CLAMP_ADDRESSMODE | |
  30405. * | 1 | WRAP_ADDRESSMODE | |
  30406. * | 2 | MIRROR_ADDRESSMODE | |
  30407. */
  30408. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30409. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30410. this.isCube = false;
  30411. this.is3D = false;
  30412. this.gammaSpace = true;
  30413. this.invertZ = false;
  30414. this.lodLevelInAlpha = false;
  30415. this.isRenderTarget = false;
  30416. this.animations = new Array();
  30417. /**
  30418. * An event triggered when the texture is disposed.
  30419. */
  30420. this.onDisposeObservable = new BABYLON.Observable();
  30421. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30422. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30423. if (this._scene) {
  30424. this._scene.textures.push(this);
  30425. }
  30426. this._uid = null;
  30427. }
  30428. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30429. get: function () {
  30430. return this._hasAlpha;
  30431. },
  30432. set: function (value) {
  30433. if (this._hasAlpha === value) {
  30434. return;
  30435. }
  30436. this._hasAlpha = value;
  30437. if (this._scene) {
  30438. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30439. }
  30440. },
  30441. enumerable: true,
  30442. configurable: true
  30443. });
  30444. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30445. get: function () {
  30446. return this._coordinatesMode;
  30447. },
  30448. /**
  30449. * How a texture is mapped.
  30450. *
  30451. * | Value | Type | Description |
  30452. * | ----- | ----------------------------------- | ----------- |
  30453. * | 0 | EXPLICIT_MODE | |
  30454. * | 1 | SPHERICAL_MODE | |
  30455. * | 2 | PLANAR_MODE | |
  30456. * | 3 | CUBIC_MODE | |
  30457. * | 4 | PROJECTION_MODE | |
  30458. * | 5 | SKYBOX_MODE | |
  30459. * | 6 | INVCUBIC_MODE | |
  30460. * | 7 | EQUIRECTANGULAR_MODE | |
  30461. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30462. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30463. */
  30464. set: function (value) {
  30465. if (this._coordinatesMode === value) {
  30466. return;
  30467. }
  30468. this._coordinatesMode = value;
  30469. if (this._scene) {
  30470. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30471. }
  30472. },
  30473. enumerable: true,
  30474. configurable: true
  30475. });
  30476. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30477. /**
  30478. * Gets whether or not the texture contains RGBD data.
  30479. */
  30480. get: function () {
  30481. return this._texture != null && this._texture._isRGBD;
  30482. },
  30483. enumerable: true,
  30484. configurable: true
  30485. });
  30486. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30487. get: function () {
  30488. if (this._texture)
  30489. return this._texture._lodGenerationOffset;
  30490. return 0.0;
  30491. },
  30492. set: function (value) {
  30493. if (this._texture)
  30494. this._texture._lodGenerationOffset = value;
  30495. },
  30496. enumerable: true,
  30497. configurable: true
  30498. });
  30499. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30500. get: function () {
  30501. if (this._texture)
  30502. return this._texture._lodGenerationScale;
  30503. return 0.0;
  30504. },
  30505. set: function (value) {
  30506. if (this._texture)
  30507. this._texture._lodGenerationScale = value;
  30508. },
  30509. enumerable: true,
  30510. configurable: true
  30511. });
  30512. Object.defineProperty(BaseTexture.prototype, "uid", {
  30513. get: function () {
  30514. if (!this._uid) {
  30515. this._uid = BABYLON.Tools.RandomId();
  30516. }
  30517. return this._uid;
  30518. },
  30519. enumerable: true,
  30520. configurable: true
  30521. });
  30522. BaseTexture.prototype.toString = function () {
  30523. return this.name;
  30524. };
  30525. BaseTexture.prototype.getClassName = function () {
  30526. return "BaseTexture";
  30527. };
  30528. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30529. set: function (callback) {
  30530. if (this._onDisposeObserver) {
  30531. this.onDisposeObservable.remove(this._onDisposeObserver);
  30532. }
  30533. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30534. },
  30535. enumerable: true,
  30536. configurable: true
  30537. });
  30538. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30539. get: function () {
  30540. return true;
  30541. },
  30542. enumerable: true,
  30543. configurable: true
  30544. });
  30545. BaseTexture.prototype.getScene = function () {
  30546. return this._scene;
  30547. };
  30548. BaseTexture.prototype.getTextureMatrix = function () {
  30549. return BABYLON.Matrix.IdentityReadOnly;
  30550. };
  30551. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30552. return BABYLON.Matrix.IdentityReadOnly;
  30553. };
  30554. BaseTexture.prototype.getInternalTexture = function () {
  30555. return this._texture;
  30556. };
  30557. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30558. return !this.isBlocking || this.isReady();
  30559. };
  30560. BaseTexture.prototype.isReady = function () {
  30561. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30562. this.delayLoad();
  30563. return false;
  30564. }
  30565. if (this._texture) {
  30566. return this._texture.isReady;
  30567. }
  30568. return false;
  30569. };
  30570. BaseTexture.prototype.getSize = function () {
  30571. if (this._texture && this._texture.width) {
  30572. return new BABYLON.Size(this._texture.width, this._texture.height);
  30573. }
  30574. if (this._texture && this._texture._size) {
  30575. return new BABYLON.Size(this._texture._size, this._texture._size);
  30576. }
  30577. return BABYLON.Size.Zero();
  30578. };
  30579. BaseTexture.prototype.getBaseSize = function () {
  30580. if (!this.isReady() || !this._texture)
  30581. return BABYLON.Size.Zero();
  30582. if (this._texture._size) {
  30583. return new BABYLON.Size(this._texture._size, this._texture._size);
  30584. }
  30585. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30586. };
  30587. BaseTexture.prototype.scale = function (ratio) {
  30588. };
  30589. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30590. get: function () {
  30591. return false;
  30592. },
  30593. enumerable: true,
  30594. configurable: true
  30595. });
  30596. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30597. if (!this._scene) {
  30598. return null;
  30599. }
  30600. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30601. for (var index = 0; index < texturesCache.length; index++) {
  30602. var texturesCacheEntry = texturesCache[index];
  30603. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30604. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30605. texturesCacheEntry.incrementReferences();
  30606. return texturesCacheEntry;
  30607. }
  30608. }
  30609. }
  30610. return null;
  30611. };
  30612. BaseTexture.prototype._rebuild = function () {
  30613. };
  30614. BaseTexture.prototype.delayLoad = function () {
  30615. };
  30616. BaseTexture.prototype.clone = function () {
  30617. return null;
  30618. };
  30619. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30620. get: function () {
  30621. if (!this._texture) {
  30622. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30623. }
  30624. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30625. },
  30626. enumerable: true,
  30627. configurable: true
  30628. });
  30629. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30630. get: function () {
  30631. if (!this._texture) {
  30632. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30633. }
  30634. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30635. },
  30636. enumerable: true,
  30637. configurable: true
  30638. });
  30639. /**
  30640. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30641. * This will returns an RGBA array buffer containing either in values (0-255) or
  30642. * float values (0-1) depending of the underlying buffer type.
  30643. * @param faceIndex The face of the texture to read (in case of cube texture)
  30644. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30645. * @returns The Array buffer containing the pixels data.
  30646. */
  30647. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30648. if (faceIndex === void 0) { faceIndex = 0; }
  30649. if (level === void 0) { level = 0; }
  30650. if (!this._texture) {
  30651. return null;
  30652. }
  30653. var size = this.getSize();
  30654. var width = size.width;
  30655. var height = size.height;
  30656. var scene = this.getScene();
  30657. if (!scene) {
  30658. return null;
  30659. }
  30660. var engine = scene.getEngine();
  30661. if (level != 0) {
  30662. width = width / Math.pow(2, level);
  30663. height = height / Math.pow(2, level);
  30664. width = Math.round(width);
  30665. height = Math.round(height);
  30666. }
  30667. if (this._texture.isCube) {
  30668. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30669. }
  30670. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30671. };
  30672. BaseTexture.prototype.releaseInternalTexture = function () {
  30673. if (this._texture) {
  30674. this._texture.dispose();
  30675. this._texture = null;
  30676. }
  30677. };
  30678. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30679. get: function () {
  30680. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30681. return null;
  30682. }
  30683. if (!this._texture._sphericalPolynomial) {
  30684. this._texture._sphericalPolynomial =
  30685. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30686. }
  30687. return this._texture._sphericalPolynomial;
  30688. },
  30689. set: function (value) {
  30690. if (this._texture) {
  30691. this._texture._sphericalPolynomial = value;
  30692. }
  30693. },
  30694. enumerable: true,
  30695. configurable: true
  30696. });
  30697. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30698. get: function () {
  30699. if (this._texture) {
  30700. return this._texture._lodTextureHigh;
  30701. }
  30702. return null;
  30703. },
  30704. enumerable: true,
  30705. configurable: true
  30706. });
  30707. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30708. get: function () {
  30709. if (this._texture) {
  30710. return this._texture._lodTextureMid;
  30711. }
  30712. return null;
  30713. },
  30714. enumerable: true,
  30715. configurable: true
  30716. });
  30717. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30718. get: function () {
  30719. if (this._texture) {
  30720. return this._texture._lodTextureLow;
  30721. }
  30722. return null;
  30723. },
  30724. enumerable: true,
  30725. configurable: true
  30726. });
  30727. BaseTexture.prototype.dispose = function () {
  30728. if (!this._scene) {
  30729. return;
  30730. }
  30731. // Animations
  30732. this._scene.stopAnimation(this);
  30733. // Remove from scene
  30734. this._scene._removePendingData(this);
  30735. var index = this._scene.textures.indexOf(this);
  30736. if (index >= 0) {
  30737. this._scene.textures.splice(index, 1);
  30738. }
  30739. if (this._texture === undefined) {
  30740. return;
  30741. }
  30742. // Release
  30743. this.releaseInternalTexture();
  30744. // Callback
  30745. this.onDisposeObservable.notifyObservers(this);
  30746. this.onDisposeObservable.clear();
  30747. };
  30748. BaseTexture.prototype.serialize = function () {
  30749. if (!this.name) {
  30750. return null;
  30751. }
  30752. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30753. // Animations
  30754. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30755. return serializationObject;
  30756. };
  30757. BaseTexture.WhenAllReady = function (textures, callback) {
  30758. var numRemaining = textures.length;
  30759. if (numRemaining === 0) {
  30760. callback();
  30761. return;
  30762. }
  30763. var _loop_1 = function () {
  30764. texture = textures[i];
  30765. if (texture.isReady()) {
  30766. if (--numRemaining === 0) {
  30767. callback();
  30768. }
  30769. }
  30770. else {
  30771. onLoadObservable = texture.onLoadObservable;
  30772. var onLoadCallback_1 = function () {
  30773. onLoadObservable.removeCallback(onLoadCallback_1);
  30774. if (--numRemaining === 0) {
  30775. callback();
  30776. }
  30777. };
  30778. onLoadObservable.add(onLoadCallback_1);
  30779. }
  30780. };
  30781. var texture, onLoadObservable;
  30782. for (var i = 0; i < textures.length; i++) {
  30783. _loop_1();
  30784. }
  30785. };
  30786. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30787. __decorate([
  30788. BABYLON.serialize()
  30789. ], BaseTexture.prototype, "name", void 0);
  30790. __decorate([
  30791. BABYLON.serialize("hasAlpha")
  30792. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30793. __decorate([
  30794. BABYLON.serialize()
  30795. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30796. __decorate([
  30797. BABYLON.serialize()
  30798. ], BaseTexture.prototype, "level", void 0);
  30799. __decorate([
  30800. BABYLON.serialize()
  30801. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30802. __decorate([
  30803. BABYLON.serialize("coordinatesMode")
  30804. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30805. __decorate([
  30806. BABYLON.serialize()
  30807. ], BaseTexture.prototype, "wrapU", void 0);
  30808. __decorate([
  30809. BABYLON.serialize()
  30810. ], BaseTexture.prototype, "wrapV", void 0);
  30811. __decorate([
  30812. BABYLON.serialize()
  30813. ], BaseTexture.prototype, "wrapR", void 0);
  30814. __decorate([
  30815. BABYLON.serialize()
  30816. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30817. __decorate([
  30818. BABYLON.serialize()
  30819. ], BaseTexture.prototype, "isCube", void 0);
  30820. __decorate([
  30821. BABYLON.serialize()
  30822. ], BaseTexture.prototype, "is3D", void 0);
  30823. __decorate([
  30824. BABYLON.serialize()
  30825. ], BaseTexture.prototype, "gammaSpace", void 0);
  30826. __decorate([
  30827. BABYLON.serialize()
  30828. ], BaseTexture.prototype, "invertZ", void 0);
  30829. __decorate([
  30830. BABYLON.serialize()
  30831. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30832. __decorate([
  30833. BABYLON.serialize()
  30834. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30835. __decorate([
  30836. BABYLON.serialize()
  30837. ], BaseTexture.prototype, "lodGenerationScale", null);
  30838. __decorate([
  30839. BABYLON.serialize()
  30840. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30841. return BaseTexture;
  30842. }());
  30843. BABYLON.BaseTexture = BaseTexture;
  30844. })(BABYLON || (BABYLON = {}));
  30845. //# sourceMappingURL=babylon.baseTexture.js.map
  30846. var BABYLON;
  30847. (function (BABYLON) {
  30848. var Texture = /** @class */ (function (_super) {
  30849. __extends(Texture, _super);
  30850. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30851. if (noMipmap === void 0) { noMipmap = false; }
  30852. if (invertY === void 0) { invertY = true; }
  30853. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30854. if (onLoad === void 0) { onLoad = null; }
  30855. if (onError === void 0) { onError = null; }
  30856. if (buffer === void 0) { buffer = null; }
  30857. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30858. var _this = _super.call(this, scene) || this;
  30859. _this.uOffset = 0;
  30860. _this.vOffset = 0;
  30861. _this.uScale = 1.0;
  30862. _this.vScale = 1.0;
  30863. _this.uAng = 0;
  30864. _this.vAng = 0;
  30865. _this.wAng = 0;
  30866. /**
  30867. * Defines the center of rotation (U)
  30868. */
  30869. _this.uRotationCenter = 0.5;
  30870. /**
  30871. * Defines the center of rotation (V)
  30872. */
  30873. _this.vRotationCenter = 0.5;
  30874. /**
  30875. * Defines the center of rotation (W)
  30876. */
  30877. _this.wRotationCenter = 0.5;
  30878. _this._isBlocking = true;
  30879. _this.name = url || "";
  30880. _this.url = url;
  30881. _this._noMipmap = noMipmap;
  30882. _this._invertY = invertY;
  30883. _this._samplingMode = samplingMode;
  30884. _this._buffer = buffer;
  30885. _this._deleteBuffer = deleteBuffer;
  30886. if (format) {
  30887. _this._format = format;
  30888. }
  30889. scene = _this.getScene();
  30890. if (!scene) {
  30891. return _this;
  30892. }
  30893. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30894. var load = function () {
  30895. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30896. _this.onLoadObservable.notifyObservers(_this);
  30897. }
  30898. if (onLoad) {
  30899. onLoad();
  30900. }
  30901. if (!_this.isBlocking && scene) {
  30902. scene.resetCachedMaterial();
  30903. }
  30904. };
  30905. if (!_this.url) {
  30906. _this._delayedOnLoad = load;
  30907. _this._delayedOnError = onError;
  30908. return _this;
  30909. }
  30910. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30911. if (!_this._texture) {
  30912. if (!scene.useDelayedTextureLoading) {
  30913. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30914. if (deleteBuffer) {
  30915. delete _this._buffer;
  30916. }
  30917. }
  30918. else {
  30919. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30920. _this._delayedOnLoad = load;
  30921. _this._delayedOnError = onError;
  30922. }
  30923. }
  30924. else {
  30925. if (_this._texture.isReady) {
  30926. BABYLON.Tools.SetImmediate(function () { return load(); });
  30927. }
  30928. else {
  30929. _this._texture.onLoadedObservable.add(load);
  30930. }
  30931. }
  30932. return _this;
  30933. }
  30934. Object.defineProperty(Texture.prototype, "noMipmap", {
  30935. get: function () {
  30936. return this._noMipmap;
  30937. },
  30938. enumerable: true,
  30939. configurable: true
  30940. });
  30941. Object.defineProperty(Texture.prototype, "isBlocking", {
  30942. get: function () {
  30943. return this._isBlocking;
  30944. },
  30945. set: function (value) {
  30946. this._isBlocking = value;
  30947. },
  30948. enumerable: true,
  30949. configurable: true
  30950. });
  30951. Object.defineProperty(Texture.prototype, "samplingMode", {
  30952. get: function () {
  30953. return this._samplingMode;
  30954. },
  30955. enumerable: true,
  30956. configurable: true
  30957. });
  30958. /**
  30959. * Update the url (and optional buffer) of this texture if url was null during construction.
  30960. * @param url the url of the texture
  30961. * @param buffer the buffer of the texture (defaults to null)
  30962. */
  30963. Texture.prototype.updateURL = function (url, buffer) {
  30964. if (buffer === void 0) { buffer = null; }
  30965. if (this.url) {
  30966. throw new Error("URL is already set");
  30967. }
  30968. this.url = url;
  30969. this._buffer = buffer;
  30970. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30971. this.delayLoad();
  30972. };
  30973. Texture.prototype.delayLoad = function () {
  30974. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30975. return;
  30976. }
  30977. var scene = this.getScene();
  30978. if (!scene) {
  30979. return;
  30980. }
  30981. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30982. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30983. if (!this._texture) {
  30984. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30985. if (this._deleteBuffer) {
  30986. delete this._buffer;
  30987. }
  30988. }
  30989. else {
  30990. if (this._delayedOnLoad) {
  30991. if (this._texture.isReady) {
  30992. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30993. }
  30994. else {
  30995. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30996. }
  30997. }
  30998. }
  30999. this._delayedOnLoad = null;
  31000. this._delayedOnError = null;
  31001. };
  31002. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31003. if (!this._texture) {
  31004. return;
  31005. }
  31006. var scene = this.getScene();
  31007. if (!scene) {
  31008. return;
  31009. }
  31010. this._samplingMode = samplingMode;
  31011. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31012. };
  31013. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31014. x *= this.uScale;
  31015. y *= this.vScale;
  31016. x -= this.uRotationCenter * this.uScale;
  31017. y -= this.vRotationCenter * this.vScale;
  31018. z -= this.wRotationCenter;
  31019. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31020. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31021. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31022. t.z += this.wRotationCenter;
  31023. };
  31024. Texture.prototype.getTextureMatrix = function () {
  31025. var _this = this;
  31026. if (this.uOffset === this._cachedUOffset &&
  31027. this.vOffset === this._cachedVOffset &&
  31028. this.uScale === this._cachedUScale &&
  31029. this.vScale === this._cachedVScale &&
  31030. this.uAng === this._cachedUAng &&
  31031. this.vAng === this._cachedVAng &&
  31032. this.wAng === this._cachedWAng) {
  31033. return this._cachedTextureMatrix;
  31034. }
  31035. this._cachedUOffset = this.uOffset;
  31036. this._cachedVOffset = this.vOffset;
  31037. this._cachedUScale = this.uScale;
  31038. this._cachedVScale = this.vScale;
  31039. this._cachedUAng = this.uAng;
  31040. this._cachedVAng = this.vAng;
  31041. this._cachedWAng = this.wAng;
  31042. if (!this._cachedTextureMatrix) {
  31043. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31044. this._rowGenerationMatrix = new BABYLON.Matrix();
  31045. this._t0 = BABYLON.Vector3.Zero();
  31046. this._t1 = BABYLON.Vector3.Zero();
  31047. this._t2 = BABYLON.Vector3.Zero();
  31048. }
  31049. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31050. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31051. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31052. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31053. this._t1.subtractInPlace(this._t0);
  31054. this._t2.subtractInPlace(this._t0);
  31055. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31056. this._cachedTextureMatrix.m[0] = this._t1.x;
  31057. this._cachedTextureMatrix.m[1] = this._t1.y;
  31058. this._cachedTextureMatrix.m[2] = this._t1.z;
  31059. this._cachedTextureMatrix.m[4] = this._t2.x;
  31060. this._cachedTextureMatrix.m[5] = this._t2.y;
  31061. this._cachedTextureMatrix.m[6] = this._t2.z;
  31062. this._cachedTextureMatrix.m[8] = this._t0.x;
  31063. this._cachedTextureMatrix.m[9] = this._t0.y;
  31064. this._cachedTextureMatrix.m[10] = this._t0.z;
  31065. var scene = this.getScene();
  31066. if (!scene) {
  31067. return this._cachedTextureMatrix;
  31068. }
  31069. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31070. return mat.hasTexture(_this);
  31071. });
  31072. return this._cachedTextureMatrix;
  31073. };
  31074. Texture.prototype.getReflectionTextureMatrix = function () {
  31075. var _this = this;
  31076. var scene = this.getScene();
  31077. if (!scene) {
  31078. return this._cachedTextureMatrix;
  31079. }
  31080. if (this.uOffset === this._cachedUOffset &&
  31081. this.vOffset === this._cachedVOffset &&
  31082. this.uScale === this._cachedUScale &&
  31083. this.vScale === this._cachedVScale &&
  31084. this.coordinatesMode === this._cachedCoordinatesMode) {
  31085. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31086. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31087. return this._cachedTextureMatrix;
  31088. }
  31089. }
  31090. else {
  31091. return this._cachedTextureMatrix;
  31092. }
  31093. }
  31094. if (!this._cachedTextureMatrix) {
  31095. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31096. }
  31097. if (!this._projectionModeMatrix) {
  31098. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31099. }
  31100. this._cachedUOffset = this.uOffset;
  31101. this._cachedVOffset = this.vOffset;
  31102. this._cachedUScale = this.uScale;
  31103. this._cachedVScale = this.vScale;
  31104. this._cachedCoordinatesMode = this.coordinatesMode;
  31105. switch (this.coordinatesMode) {
  31106. case Texture.PLANAR_MODE:
  31107. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31108. this._cachedTextureMatrix[0] = this.uScale;
  31109. this._cachedTextureMatrix[5] = this.vScale;
  31110. this._cachedTextureMatrix[12] = this.uOffset;
  31111. this._cachedTextureMatrix[13] = this.vOffset;
  31112. break;
  31113. case Texture.PROJECTION_MODE:
  31114. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31115. this._projectionModeMatrix.m[0] = 0.5;
  31116. this._projectionModeMatrix.m[5] = -0.5;
  31117. this._projectionModeMatrix.m[10] = 0.0;
  31118. this._projectionModeMatrix.m[12] = 0.5;
  31119. this._projectionModeMatrix.m[13] = 0.5;
  31120. this._projectionModeMatrix.m[14] = 1.0;
  31121. this._projectionModeMatrix.m[15] = 1.0;
  31122. var projectionMatrix = scene.getProjectionMatrix();
  31123. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31124. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31125. break;
  31126. default:
  31127. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31128. break;
  31129. }
  31130. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31131. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31132. });
  31133. return this._cachedTextureMatrix;
  31134. };
  31135. Texture.prototype.clone = function () {
  31136. var _this = this;
  31137. return BABYLON.SerializationHelper.Clone(function () {
  31138. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31139. }, this);
  31140. };
  31141. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31142. get: function () {
  31143. if (!this._onLoadObservable) {
  31144. this._onLoadObservable = new BABYLON.Observable();
  31145. }
  31146. return this._onLoadObservable;
  31147. },
  31148. enumerable: true,
  31149. configurable: true
  31150. });
  31151. Texture.prototype.serialize = function () {
  31152. var serializationObject = _super.prototype.serialize.call(this);
  31153. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31154. serializationObject.base64String = this._buffer;
  31155. serializationObject.name = serializationObject.name.replace("data:", "");
  31156. }
  31157. serializationObject.invertY = this._invertY;
  31158. serializationObject.samplingMode = this.samplingMode;
  31159. return serializationObject;
  31160. };
  31161. Texture.prototype.getClassName = function () {
  31162. return "Texture";
  31163. };
  31164. Texture.prototype.dispose = function () {
  31165. _super.prototype.dispose.call(this);
  31166. if (this.onLoadObservable) {
  31167. this.onLoadObservable.clear();
  31168. this._onLoadObservable = null;
  31169. }
  31170. this._delayedOnLoad = null;
  31171. this._delayedOnError = null;
  31172. };
  31173. // Statics
  31174. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31175. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31176. if (onLoad === void 0) { onLoad = null; }
  31177. if (onError === void 0) { onError = null; }
  31178. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31179. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31180. };
  31181. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31182. if (parsedTexture.customType) {
  31183. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31184. // Update Sampling Mode
  31185. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31186. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31187. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31188. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31189. }
  31190. }
  31191. return parsedCustomTexture;
  31192. }
  31193. if (parsedTexture.isCube) {
  31194. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31195. }
  31196. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31197. return null;
  31198. }
  31199. var texture = BABYLON.SerializationHelper.Parse(function () {
  31200. var generateMipMaps = true;
  31201. if (parsedTexture.noMipmap) {
  31202. generateMipMaps = false;
  31203. }
  31204. if (parsedTexture.mirrorPlane) {
  31205. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31206. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31207. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31208. return mirrorTexture;
  31209. }
  31210. else if (parsedTexture.isRenderTarget) {
  31211. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31212. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31213. return renderTargetTexture;
  31214. }
  31215. else {
  31216. var texture;
  31217. if (parsedTexture.base64String) {
  31218. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31219. }
  31220. else {
  31221. var url = rootUrl + parsedTexture.name;
  31222. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31223. url = parsedTexture.url;
  31224. }
  31225. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31226. }
  31227. return texture;
  31228. }
  31229. }, parsedTexture, scene);
  31230. // Update Sampling Mode
  31231. if (parsedTexture.samplingMode) {
  31232. var sampling = parsedTexture.samplingMode;
  31233. if (texture._samplingMode !== sampling) {
  31234. texture.updateSamplingMode(sampling);
  31235. }
  31236. }
  31237. // Animations
  31238. if (parsedTexture.animations) {
  31239. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31240. var parsedAnimation = parsedTexture.animations[animationIndex];
  31241. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31242. }
  31243. }
  31244. return texture;
  31245. };
  31246. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31247. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31248. if (noMipmap === void 0) { noMipmap = false; }
  31249. if (invertY === void 0) { invertY = true; }
  31250. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31251. if (onLoad === void 0) { onLoad = null; }
  31252. if (onError === void 0) { onError = null; }
  31253. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31254. if (name.substr(0, 5) !== "data:") {
  31255. name = "data:" + name;
  31256. }
  31257. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31258. };
  31259. // Constants
  31260. Texture.NEAREST_SAMPLINGMODE = 1;
  31261. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31262. Texture.BILINEAR_SAMPLINGMODE = 2;
  31263. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31264. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31265. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31266. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31267. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31268. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31269. Texture.NEAREST_LINEAR = 7;
  31270. Texture.NEAREST_NEAREST = 8;
  31271. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31272. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31273. Texture.LINEAR_LINEAR = 11;
  31274. Texture.LINEAR_NEAREST = 12;
  31275. Texture.EXPLICIT_MODE = 0;
  31276. Texture.SPHERICAL_MODE = 1;
  31277. Texture.PLANAR_MODE = 2;
  31278. Texture.CUBIC_MODE = 3;
  31279. Texture.PROJECTION_MODE = 4;
  31280. Texture.SKYBOX_MODE = 5;
  31281. Texture.INVCUBIC_MODE = 6;
  31282. Texture.EQUIRECTANGULAR_MODE = 7;
  31283. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31284. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31285. Texture.CLAMP_ADDRESSMODE = 0;
  31286. Texture.WRAP_ADDRESSMODE = 1;
  31287. Texture.MIRROR_ADDRESSMODE = 2;
  31288. /**
  31289. * 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
  31290. */
  31291. Texture.UseSerializedUrlIfAny = false;
  31292. __decorate([
  31293. BABYLON.serialize()
  31294. ], Texture.prototype, "url", void 0);
  31295. __decorate([
  31296. BABYLON.serialize()
  31297. ], Texture.prototype, "uOffset", void 0);
  31298. __decorate([
  31299. BABYLON.serialize()
  31300. ], Texture.prototype, "vOffset", void 0);
  31301. __decorate([
  31302. BABYLON.serialize()
  31303. ], Texture.prototype, "uScale", void 0);
  31304. __decorate([
  31305. BABYLON.serialize()
  31306. ], Texture.prototype, "vScale", void 0);
  31307. __decorate([
  31308. BABYLON.serialize()
  31309. ], Texture.prototype, "uAng", void 0);
  31310. __decorate([
  31311. BABYLON.serialize()
  31312. ], Texture.prototype, "vAng", void 0);
  31313. __decorate([
  31314. BABYLON.serialize()
  31315. ], Texture.prototype, "wAng", void 0);
  31316. __decorate([
  31317. BABYLON.serialize()
  31318. ], Texture.prototype, "uRotationCenter", void 0);
  31319. __decorate([
  31320. BABYLON.serialize()
  31321. ], Texture.prototype, "vRotationCenter", void 0);
  31322. __decorate([
  31323. BABYLON.serialize()
  31324. ], Texture.prototype, "wRotationCenter", void 0);
  31325. __decorate([
  31326. BABYLON.serialize()
  31327. ], Texture.prototype, "isBlocking", null);
  31328. return Texture;
  31329. }(BABYLON.BaseTexture));
  31330. BABYLON.Texture = Texture;
  31331. })(BABYLON || (BABYLON = {}));
  31332. //# sourceMappingURL=babylon.texture.js.map
  31333. var BABYLON;
  31334. (function (BABYLON) {
  31335. /**
  31336. * @hidden
  31337. **/
  31338. var _InstancesBatch = /** @class */ (function () {
  31339. function _InstancesBatch() {
  31340. this.mustReturn = false;
  31341. this.visibleInstances = new Array();
  31342. this.renderSelf = new Array();
  31343. }
  31344. return _InstancesBatch;
  31345. }());
  31346. BABYLON._InstancesBatch = _InstancesBatch;
  31347. var Mesh = /** @class */ (function (_super) {
  31348. __extends(Mesh, _super);
  31349. /**
  31350. * @constructor
  31351. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31352. * @param {Scene} scene The scene to add this mesh to.
  31353. * @param {Node} parent The parent of this mesh, if it has one
  31354. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31355. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31356. * When false, achieved by calling a clone(), also passing False.
  31357. * This will make creation of children, recursive.
  31358. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31359. */
  31360. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31361. if (scene === void 0) { scene = null; }
  31362. if (parent === void 0) { parent = null; }
  31363. if (source === void 0) { source = null; }
  31364. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31365. var _this = _super.call(this, name, scene) || this;
  31366. // Events
  31367. /**
  31368. * An event triggered before rendering the mesh
  31369. */
  31370. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31371. /**
  31372. * An event triggered after rendering the mesh
  31373. */
  31374. _this.onAfterRenderObservable = new BABYLON.Observable();
  31375. /**
  31376. * An event triggered before drawing the mesh
  31377. */
  31378. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31379. // Members
  31380. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31381. _this.instances = new Array();
  31382. _this._LODLevels = new Array();
  31383. _this._visibleInstances = {};
  31384. _this._renderIdForInstances = new Array();
  31385. _this._batchCache = new _InstancesBatch();
  31386. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31387. // Use by builder only to know what orientation were the mesh build in.
  31388. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31389. _this.overrideMaterialSideOrientation = null;
  31390. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31391. // Will be used to save a source mesh reference, If any
  31392. _this._source = null;
  31393. scene = _this.getScene();
  31394. if (source) {
  31395. // Geometry
  31396. if (source._geometry) {
  31397. source._geometry.applyToMesh(_this);
  31398. }
  31399. // Deep copy
  31400. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31401. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31402. // Source mesh
  31403. _this._source = source;
  31404. // Metadata
  31405. if (source.metadata && source.metadata.clone) {
  31406. _this.metadata = source.metadata.clone();
  31407. }
  31408. else {
  31409. _this.metadata = source.metadata;
  31410. }
  31411. // Tags
  31412. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31413. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31414. }
  31415. // Parent
  31416. _this.parent = source.parent;
  31417. // Pivot
  31418. _this.setPivotMatrix(source.getPivotMatrix());
  31419. _this.id = name + "." + source.id;
  31420. // Material
  31421. _this.material = source.material;
  31422. var index;
  31423. if (!doNotCloneChildren) {
  31424. // Children
  31425. var directDescendants = source.getDescendants(true);
  31426. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31427. var child = directDescendants[index_1];
  31428. if (child.clone) {
  31429. child.clone(name + "." + child.name, _this);
  31430. }
  31431. }
  31432. }
  31433. // Physics clone
  31434. var physicsEngine = _this.getScene().getPhysicsEngine();
  31435. if (clonePhysicsImpostor && physicsEngine) {
  31436. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31437. if (impostor) {
  31438. _this.physicsImpostor = impostor.clone(_this);
  31439. }
  31440. }
  31441. // Particles
  31442. for (index = 0; index < scene.particleSystems.length; index++) {
  31443. var system = scene.particleSystems[index];
  31444. if (system.emitter === source) {
  31445. system.clone(system.name, _this);
  31446. }
  31447. }
  31448. _this.computeWorldMatrix(true);
  31449. }
  31450. // Parent
  31451. if (parent !== null) {
  31452. _this.parent = parent;
  31453. }
  31454. return _this;
  31455. }
  31456. Object.defineProperty(Mesh, "FRONTSIDE", {
  31457. /**
  31458. * Mesh side orientation : usually the external or front surface
  31459. */
  31460. get: function () {
  31461. return Mesh._FRONTSIDE;
  31462. },
  31463. enumerable: true,
  31464. configurable: true
  31465. });
  31466. Object.defineProperty(Mesh, "BACKSIDE", {
  31467. /**
  31468. * Mesh side orientation : usually the internal or back surface
  31469. */
  31470. get: function () {
  31471. return Mesh._BACKSIDE;
  31472. },
  31473. enumerable: true,
  31474. configurable: true
  31475. });
  31476. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31477. /**
  31478. * Mesh side orientation : both internal and external or front and back surfaces
  31479. */
  31480. get: function () {
  31481. return Mesh._DOUBLESIDE;
  31482. },
  31483. enumerable: true,
  31484. configurable: true
  31485. });
  31486. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31487. /**
  31488. * Mesh side orientation : by default, `FRONTSIDE`
  31489. */
  31490. get: function () {
  31491. return Mesh._DEFAULTSIDE;
  31492. },
  31493. enumerable: true,
  31494. configurable: true
  31495. });
  31496. Object.defineProperty(Mesh, "NO_CAP", {
  31497. /**
  31498. * Mesh cap setting : no cap
  31499. */
  31500. get: function () {
  31501. return Mesh._NO_CAP;
  31502. },
  31503. enumerable: true,
  31504. configurable: true
  31505. });
  31506. Object.defineProperty(Mesh, "CAP_START", {
  31507. /**
  31508. * Mesh cap setting : one cap at the beginning of the mesh
  31509. */
  31510. get: function () {
  31511. return Mesh._CAP_START;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. Object.defineProperty(Mesh, "CAP_END", {
  31517. /**
  31518. * Mesh cap setting : one cap at the end of the mesh
  31519. */
  31520. get: function () {
  31521. return Mesh._CAP_END;
  31522. },
  31523. enumerable: true,
  31524. configurable: true
  31525. });
  31526. Object.defineProperty(Mesh, "CAP_ALL", {
  31527. /**
  31528. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31529. */
  31530. get: function () {
  31531. return Mesh._CAP_ALL;
  31532. },
  31533. enumerable: true,
  31534. configurable: true
  31535. });
  31536. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31537. set: function (callback) {
  31538. if (this._onBeforeDrawObserver) {
  31539. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31540. }
  31541. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31547. get: function () {
  31548. return this._morphTargetManager;
  31549. },
  31550. set: function (value) {
  31551. if (this._morphTargetManager === value) {
  31552. return;
  31553. }
  31554. this._morphTargetManager = value;
  31555. this._syncGeometryWithMorphTargetManager();
  31556. },
  31557. enumerable: true,
  31558. configurable: true
  31559. });
  31560. Object.defineProperty(Mesh.prototype, "source", {
  31561. get: function () {
  31562. return this._source;
  31563. },
  31564. enumerable: true,
  31565. configurable: true
  31566. });
  31567. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31568. get: function () {
  31569. return this._unIndexed;
  31570. },
  31571. set: function (value) {
  31572. if (this._unIndexed !== value) {
  31573. this._unIndexed = value;
  31574. this._markSubMeshesAsAttributesDirty();
  31575. }
  31576. },
  31577. enumerable: true,
  31578. configurable: true
  31579. });
  31580. // Methods
  31581. /**
  31582. * Returns the string "Mesh".
  31583. */
  31584. Mesh.prototype.getClassName = function () {
  31585. return "Mesh";
  31586. };
  31587. /**
  31588. * Returns a string.
  31589. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31590. */
  31591. Mesh.prototype.toString = function (fullDetails) {
  31592. var ret = _super.prototype.toString.call(this, fullDetails);
  31593. ret += ", n vertices: " + this.getTotalVertices();
  31594. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31595. if (this.animations) {
  31596. for (var i = 0; i < this.animations.length; i++) {
  31597. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31598. }
  31599. }
  31600. if (fullDetails) {
  31601. if (this._geometry) {
  31602. var ib = this.getIndices();
  31603. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31604. if (vb && ib) {
  31605. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31606. }
  31607. }
  31608. else {
  31609. ret += ", flat shading: UNKNOWN";
  31610. }
  31611. }
  31612. return ret;
  31613. };
  31614. Mesh.prototype._unBindEffect = function () {
  31615. _super.prototype._unBindEffect.call(this);
  31616. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31617. var instance = _a[_i];
  31618. instance._unBindEffect();
  31619. }
  31620. };
  31621. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31622. /**
  31623. * True if the mesh has some Levels Of Details (LOD).
  31624. * Returns a boolean.
  31625. */
  31626. get: function () {
  31627. return this._LODLevels.length > 0;
  31628. },
  31629. enumerable: true,
  31630. configurable: true
  31631. });
  31632. /**
  31633. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31634. * @returns an array of {BABYLON.MeshLODLevel}
  31635. */
  31636. Mesh.prototype.getLODLevels = function () {
  31637. return this._LODLevels;
  31638. };
  31639. Mesh.prototype._sortLODLevels = function () {
  31640. this._LODLevels.sort(function (a, b) {
  31641. if (a.distance < b.distance) {
  31642. return 1;
  31643. }
  31644. if (a.distance > b.distance) {
  31645. return -1;
  31646. }
  31647. return 0;
  31648. });
  31649. };
  31650. /**
  31651. * Add a mesh as LOD level triggered at the given distance.
  31652. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31653. * @param distance The distance from the center of the object to show this level
  31654. * @param mesh The mesh to be added as LOD level (can be null)
  31655. * @return This mesh (for chaining)
  31656. */
  31657. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31658. if (mesh && mesh._masterMesh) {
  31659. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31660. return this;
  31661. }
  31662. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31663. this._LODLevels.push(level);
  31664. if (mesh) {
  31665. mesh._masterMesh = this;
  31666. }
  31667. this._sortLODLevels();
  31668. return this;
  31669. };
  31670. /**
  31671. * Returns the LOD level mesh at the passed distance or null if not found.
  31672. * It is related to the method `addLODLevel(distance, mesh)`.
  31673. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31674. * Returns an object Mesh or `null`.
  31675. */
  31676. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31677. for (var index = 0; index < this._LODLevels.length; index++) {
  31678. var level = this._LODLevels[index];
  31679. if (level.distance === distance) {
  31680. return level.mesh;
  31681. }
  31682. }
  31683. return null;
  31684. };
  31685. /**
  31686. * Remove a mesh from the LOD array
  31687. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31688. * @param {Mesh} mesh The mesh to be removed.
  31689. * @return {Mesh} This mesh (for chaining)
  31690. */
  31691. Mesh.prototype.removeLODLevel = function (mesh) {
  31692. for (var index = 0; index < this._LODLevels.length; index++) {
  31693. if (this._LODLevels[index].mesh === mesh) {
  31694. this._LODLevels.splice(index, 1);
  31695. if (mesh) {
  31696. mesh._masterMesh = null;
  31697. }
  31698. }
  31699. }
  31700. this._sortLODLevels();
  31701. return this;
  31702. };
  31703. /**
  31704. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31705. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31706. */
  31707. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31708. if (!this._LODLevels || this._LODLevels.length === 0) {
  31709. return this;
  31710. }
  31711. var bSphere;
  31712. if (boundingSphere) {
  31713. bSphere = boundingSphere;
  31714. }
  31715. else {
  31716. var boundingInfo = this.getBoundingInfo();
  31717. bSphere = boundingInfo.boundingSphere;
  31718. }
  31719. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31720. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31721. if (this.onLODLevelSelection) {
  31722. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31723. }
  31724. return this;
  31725. }
  31726. for (var index = 0; index < this._LODLevels.length; index++) {
  31727. var level = this._LODLevels[index];
  31728. if (level.distance < distanceToCamera) {
  31729. if (level.mesh) {
  31730. level.mesh._preActivate();
  31731. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31732. }
  31733. if (this.onLODLevelSelection) {
  31734. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31735. }
  31736. return level.mesh;
  31737. }
  31738. }
  31739. if (this.onLODLevelSelection) {
  31740. this.onLODLevelSelection(distanceToCamera, this, this);
  31741. }
  31742. return this;
  31743. };
  31744. Object.defineProperty(Mesh.prototype, "geometry", {
  31745. /**
  31746. * Returns the mesh internal Geometry object.
  31747. */
  31748. get: function () {
  31749. return this._geometry;
  31750. },
  31751. enumerable: true,
  31752. configurable: true
  31753. });
  31754. /**
  31755. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31756. */
  31757. Mesh.prototype.getTotalVertices = function () {
  31758. if (this._geometry === null || this._geometry === undefined) {
  31759. return 0;
  31760. }
  31761. return this._geometry.getTotalVertices();
  31762. };
  31763. /**
  31764. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31765. * 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.
  31766. * You can force the copy with forceCopy === true
  31767. * Returns null if the mesh has no geometry or no vertex buffer.
  31768. * Possible `kind` values :
  31769. * - BABYLON.VertexBuffer.PositionKind
  31770. * - BABYLON.VertexBuffer.UVKind
  31771. * - BABYLON.VertexBuffer.UV2Kind
  31772. * - BABYLON.VertexBuffer.UV3Kind
  31773. * - BABYLON.VertexBuffer.UV4Kind
  31774. * - BABYLON.VertexBuffer.UV5Kind
  31775. * - BABYLON.VertexBuffer.UV6Kind
  31776. * - BABYLON.VertexBuffer.ColorKind
  31777. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31778. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31779. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31780. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31781. */
  31782. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31783. if (!this._geometry) {
  31784. return null;
  31785. }
  31786. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31787. };
  31788. /**
  31789. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31790. * Returns `null` if the mesh has no geometry.
  31791. * Possible `kind` values :
  31792. * - BABYLON.VertexBuffer.PositionKind
  31793. * - BABYLON.VertexBuffer.UVKind
  31794. * - BABYLON.VertexBuffer.UV2Kind
  31795. * - BABYLON.VertexBuffer.UV3Kind
  31796. * - BABYLON.VertexBuffer.UV4Kind
  31797. * - BABYLON.VertexBuffer.UV5Kind
  31798. * - BABYLON.VertexBuffer.UV6Kind
  31799. * - BABYLON.VertexBuffer.ColorKind
  31800. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31801. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31802. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31803. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31804. */
  31805. Mesh.prototype.getVertexBuffer = function (kind) {
  31806. if (!this._geometry) {
  31807. return null;
  31808. }
  31809. return this._geometry.getVertexBuffer(kind);
  31810. };
  31811. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31812. if (!this._geometry) {
  31813. if (this._delayInfo) {
  31814. return this._delayInfo.indexOf(kind) !== -1;
  31815. }
  31816. return false;
  31817. }
  31818. return this._geometry.isVerticesDataPresent(kind);
  31819. };
  31820. /**
  31821. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31822. * Possible `kind` values :
  31823. * - BABYLON.VertexBuffer.PositionKind
  31824. * - BABYLON.VertexBuffer.UVKind
  31825. * - BABYLON.VertexBuffer.UV2Kind
  31826. * - BABYLON.VertexBuffer.UV3Kind
  31827. * - BABYLON.VertexBuffer.UV4Kind
  31828. * - BABYLON.VertexBuffer.UV5Kind
  31829. * - BABYLON.VertexBuffer.UV6Kind
  31830. * - BABYLON.VertexBuffer.ColorKind
  31831. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31832. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31833. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31834. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31835. */
  31836. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31837. if (!this._geometry) {
  31838. if (this._delayInfo) {
  31839. return this._delayInfo.indexOf(kind) !== -1;
  31840. }
  31841. return false;
  31842. }
  31843. return this._geometry.isVertexBufferUpdatable(kind);
  31844. };
  31845. /**
  31846. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31847. * Possible `kind` values :
  31848. * - BABYLON.VertexBuffer.PositionKind
  31849. * - BABYLON.VertexBuffer.UVKind
  31850. * - BABYLON.VertexBuffer.UV2Kind
  31851. * - BABYLON.VertexBuffer.UV3Kind
  31852. * - BABYLON.VertexBuffer.UV4Kind
  31853. * - BABYLON.VertexBuffer.UV5Kind
  31854. * - BABYLON.VertexBuffer.UV6Kind
  31855. * - BABYLON.VertexBuffer.ColorKind
  31856. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31857. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31858. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31859. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31860. */
  31861. Mesh.prototype.getVerticesDataKinds = function () {
  31862. if (!this._geometry) {
  31863. var result = new Array();
  31864. if (this._delayInfo) {
  31865. this._delayInfo.forEach(function (kind, index, array) {
  31866. result.push(kind);
  31867. });
  31868. }
  31869. return result;
  31870. }
  31871. return this._geometry.getVerticesDataKinds();
  31872. };
  31873. /**
  31874. * Returns a positive integer : the total number of indices in this mesh geometry.
  31875. * Returns zero if the mesh has no geometry.
  31876. */
  31877. Mesh.prototype.getTotalIndices = function () {
  31878. if (!this._geometry) {
  31879. return 0;
  31880. }
  31881. return this._geometry.getTotalIndices();
  31882. };
  31883. /**
  31884. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31885. * 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.
  31886. * Returns an empty array if the mesh has no geometry.
  31887. */
  31888. Mesh.prototype.getIndices = function (copyWhenShared) {
  31889. if (!this._geometry) {
  31890. return [];
  31891. }
  31892. return this._geometry.getIndices(copyWhenShared);
  31893. };
  31894. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31895. get: function () {
  31896. return this._masterMesh !== null && this._masterMesh !== undefined;
  31897. },
  31898. enumerable: true,
  31899. configurable: true
  31900. });
  31901. /**
  31902. * Determine if the current mesh is ready to be rendered
  31903. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31904. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31905. * @returns true if all associated assets are ready (material, textures, shaders)
  31906. */
  31907. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31908. if (completeCheck === void 0) { completeCheck = false; }
  31909. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31910. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31911. return false;
  31912. }
  31913. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31914. return false;
  31915. }
  31916. if (!this.subMeshes || this.subMeshes.length === 0) {
  31917. return true;
  31918. }
  31919. if (!completeCheck) {
  31920. return true;
  31921. }
  31922. var engine = this.getEngine();
  31923. var scene = this.getScene();
  31924. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31925. this.computeWorldMatrix();
  31926. var mat = this.material || scene.defaultMaterial;
  31927. if (mat) {
  31928. if (mat.storeEffectOnSubMeshes) {
  31929. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31930. var subMesh = _a[_i];
  31931. var effectiveMaterial = subMesh.getMaterial();
  31932. if (effectiveMaterial) {
  31933. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31934. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31935. return false;
  31936. }
  31937. }
  31938. else {
  31939. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31940. return false;
  31941. }
  31942. }
  31943. }
  31944. }
  31945. }
  31946. else {
  31947. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31948. return false;
  31949. }
  31950. }
  31951. }
  31952. // Shadows
  31953. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31954. var light = _c[_b];
  31955. var generator = light.getShadowGenerator();
  31956. if (generator) {
  31957. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31958. var subMesh = _e[_d];
  31959. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31960. return false;
  31961. }
  31962. }
  31963. }
  31964. }
  31965. // LOD
  31966. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31967. var lod = _g[_f];
  31968. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31969. return false;
  31970. }
  31971. }
  31972. return true;
  31973. };
  31974. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31975. /**
  31976. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31977. * This property is pertinent only for updatable parametric shapes.
  31978. */
  31979. get: function () {
  31980. return this._areNormalsFrozen;
  31981. },
  31982. enumerable: true,
  31983. configurable: true
  31984. });
  31985. /**
  31986. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31987. * It has no effect at all on other shapes.
  31988. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31989. * Returns the Mesh.
  31990. */
  31991. Mesh.prototype.freezeNormals = function () {
  31992. this._areNormalsFrozen = true;
  31993. return this;
  31994. };
  31995. /**
  31996. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31997. * It has no effect at all on other shapes.
  31998. * It reactivates the mesh normals computation if it was previously frozen.
  31999. * Returns the Mesh.
  32000. */
  32001. Mesh.prototype.unfreezeNormals = function () {
  32002. this._areNormalsFrozen = false;
  32003. return this;
  32004. };
  32005. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32006. /**
  32007. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32008. */
  32009. set: function (count) {
  32010. this._overridenInstanceCount = count;
  32011. },
  32012. enumerable: true,
  32013. configurable: true
  32014. });
  32015. // Methods
  32016. Mesh.prototype._preActivate = function () {
  32017. var sceneRenderId = this.getScene().getRenderId();
  32018. if (this._preActivateId === sceneRenderId) {
  32019. return this;
  32020. }
  32021. this._preActivateId = sceneRenderId;
  32022. this._visibleInstances = null;
  32023. return this;
  32024. };
  32025. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32026. if (this._visibleInstances) {
  32027. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32028. }
  32029. return this;
  32030. };
  32031. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32032. if (!this._visibleInstances) {
  32033. this._visibleInstances = {};
  32034. this._visibleInstances.defaultRenderId = renderId;
  32035. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32036. }
  32037. if (!this._visibleInstances[renderId]) {
  32038. this._visibleInstances[renderId] = new Array();
  32039. }
  32040. this._visibleInstances[renderId].push(instance);
  32041. return this;
  32042. };
  32043. /**
  32044. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32045. * This means the mesh underlying bounding box and sphere are recomputed.
  32046. * Returns the Mesh.
  32047. */
  32048. Mesh.prototype.refreshBoundingInfo = function () {
  32049. return this._refreshBoundingInfo(false);
  32050. };
  32051. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32052. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32053. return this;
  32054. }
  32055. var data = this._getPositionData(applySkeleton);
  32056. if (data) {
  32057. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32058. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32059. }
  32060. if (this.subMeshes) {
  32061. for (var index = 0; index < this.subMeshes.length; index++) {
  32062. this.subMeshes[index].refreshBoundingInfo();
  32063. }
  32064. }
  32065. this._updateBoundingInfo();
  32066. return this;
  32067. };
  32068. Mesh.prototype._getPositionData = function (applySkeleton) {
  32069. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32070. if (data && applySkeleton && this.skeleton) {
  32071. data = BABYLON.Tools.Slice(data);
  32072. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32073. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32074. if (matricesWeightsData && matricesIndicesData) {
  32075. var needExtras = this.numBoneInfluencers > 4;
  32076. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32077. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32078. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32079. var tempVector = BABYLON.Tmp.Vector3[0];
  32080. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32081. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32082. var matWeightIdx = 0;
  32083. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32084. finalMatrix.reset();
  32085. var inf;
  32086. var weight;
  32087. for (inf = 0; inf < 4; inf++) {
  32088. weight = matricesWeightsData[matWeightIdx + inf];
  32089. if (weight <= 0)
  32090. break;
  32091. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32092. finalMatrix.addToSelf(tempMatrix);
  32093. }
  32094. if (needExtras) {
  32095. for (inf = 0; inf < 4; inf++) {
  32096. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32097. if (weight <= 0)
  32098. break;
  32099. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32100. finalMatrix.addToSelf(tempMatrix);
  32101. }
  32102. }
  32103. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32104. tempVector.toArray(data, index);
  32105. }
  32106. }
  32107. }
  32108. return data;
  32109. };
  32110. Mesh.prototype._createGlobalSubMesh = function (force) {
  32111. var totalVertices = this.getTotalVertices();
  32112. if (!totalVertices || !this.getIndices()) {
  32113. return null;
  32114. }
  32115. // Check if we need to recreate the submeshes
  32116. if (this.subMeshes && this.subMeshes.length > 0) {
  32117. var ib = this.getIndices();
  32118. if (!ib) {
  32119. return null;
  32120. }
  32121. var totalIndices = ib.length;
  32122. var needToRecreate = false;
  32123. if (force) {
  32124. needToRecreate = true;
  32125. }
  32126. else {
  32127. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32128. var submesh = _a[_i];
  32129. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32130. needToRecreate = true;
  32131. break;
  32132. }
  32133. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32134. needToRecreate = true;
  32135. break;
  32136. }
  32137. }
  32138. }
  32139. if (!needToRecreate) {
  32140. return this.subMeshes[0];
  32141. }
  32142. }
  32143. this.releaseSubMeshes();
  32144. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32145. };
  32146. Mesh.prototype.subdivide = function (count) {
  32147. if (count < 1) {
  32148. return;
  32149. }
  32150. var totalIndices = this.getTotalIndices();
  32151. var subdivisionSize = (totalIndices / count) | 0;
  32152. var offset = 0;
  32153. // Ensure that subdivisionSize is a multiple of 3
  32154. while (subdivisionSize % 3 !== 0) {
  32155. subdivisionSize++;
  32156. }
  32157. this.releaseSubMeshes();
  32158. for (var index = 0; index < count; index++) {
  32159. if (offset >= totalIndices) {
  32160. break;
  32161. }
  32162. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32163. offset += subdivisionSize;
  32164. }
  32165. this.synchronizeInstances();
  32166. };
  32167. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32168. if (updatable === void 0) { updatable = false; }
  32169. if (!this._geometry) {
  32170. var vertexData = new BABYLON.VertexData();
  32171. vertexData.set(data, kind);
  32172. var scene = this.getScene();
  32173. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32174. }
  32175. else {
  32176. this._geometry.setVerticesData(kind, data, updatable, stride);
  32177. }
  32178. return this;
  32179. };
  32180. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32181. if (updatable === void 0) { updatable = true; }
  32182. var vb = this.getVertexBuffer(kind);
  32183. if (!vb || vb.isUpdatable() === updatable) {
  32184. return;
  32185. }
  32186. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32187. };
  32188. /**
  32189. * Sets the mesh VertexBuffer.
  32190. * Returns the Mesh.
  32191. */
  32192. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32193. if (!this._geometry) {
  32194. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32195. }
  32196. this._geometry.setVerticesBuffer(buffer);
  32197. return this;
  32198. };
  32199. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32200. if (!this._geometry) {
  32201. return this;
  32202. }
  32203. if (!makeItUnique) {
  32204. this._geometry.updateVerticesData(kind, data, updateExtends);
  32205. }
  32206. else {
  32207. this.makeGeometryUnique();
  32208. this.updateVerticesData(kind, data, updateExtends, false);
  32209. }
  32210. return this;
  32211. };
  32212. /**
  32213. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32214. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32215. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32216. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32217. * Returns the Mesh.
  32218. */
  32219. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32220. if (computeNormals === void 0) { computeNormals = true; }
  32221. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32222. if (!positions) {
  32223. return this;
  32224. }
  32225. positionFunction(positions);
  32226. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32227. if (computeNormals) {
  32228. var indices = this.getIndices();
  32229. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32230. if (!normals) {
  32231. return this;
  32232. }
  32233. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32234. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32235. }
  32236. return this;
  32237. };
  32238. /**
  32239. * Creates a un-shared specific occurence of the geometry for the mesh.
  32240. * Returns the Mesh.
  32241. */
  32242. Mesh.prototype.makeGeometryUnique = function () {
  32243. if (!this._geometry) {
  32244. return this;
  32245. }
  32246. var oldGeometry = this._geometry;
  32247. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32248. oldGeometry.releaseForMesh(this, true);
  32249. geometry.applyToMesh(this);
  32250. return this;
  32251. };
  32252. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32253. if (totalVertices === void 0) { totalVertices = null; }
  32254. if (updatable === void 0) { updatable = false; }
  32255. if (!this._geometry) {
  32256. var vertexData = new BABYLON.VertexData();
  32257. vertexData.indices = indices;
  32258. var scene = this.getScene();
  32259. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32260. }
  32261. else {
  32262. this._geometry.setIndices(indices, totalVertices, updatable);
  32263. }
  32264. return this;
  32265. };
  32266. /**
  32267. * Update the current index buffer
  32268. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32269. * Returns the Mesh.
  32270. */
  32271. Mesh.prototype.updateIndices = function (indices, offset) {
  32272. if (!this._geometry) {
  32273. return this;
  32274. }
  32275. this._geometry.updateIndices(indices, offset);
  32276. return this;
  32277. };
  32278. /**
  32279. * Invert the geometry to move from a right handed system to a left handed one.
  32280. * Returns the Mesh.
  32281. */
  32282. Mesh.prototype.toLeftHanded = function () {
  32283. if (!this._geometry) {
  32284. return this;
  32285. }
  32286. this._geometry.toLeftHanded();
  32287. return this;
  32288. };
  32289. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32290. if (!this._geometry) {
  32291. return this;
  32292. }
  32293. var engine = this.getScene().getEngine();
  32294. // Wireframe
  32295. var indexToBind;
  32296. if (this._unIndexed) {
  32297. indexToBind = null;
  32298. }
  32299. else {
  32300. switch (fillMode) {
  32301. case BABYLON.Material.PointFillMode:
  32302. indexToBind = null;
  32303. break;
  32304. case BABYLON.Material.WireFrameFillMode:
  32305. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32306. break;
  32307. default:
  32308. case BABYLON.Material.TriangleFillMode:
  32309. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32310. break;
  32311. }
  32312. }
  32313. // VBOs
  32314. this._geometry._bind(effect, indexToBind);
  32315. return this;
  32316. };
  32317. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32318. if (alternate === void 0) { alternate = false; }
  32319. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32320. return this;
  32321. }
  32322. this.onBeforeDrawObservable.notifyObservers(this);
  32323. var scene = this.getScene();
  32324. var engine = scene.getEngine();
  32325. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32326. // or triangles as points
  32327. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32328. }
  32329. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32330. // Triangles as wireframe
  32331. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32332. }
  32333. else {
  32334. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32335. }
  32336. if (scene._isAlternateRenderingEnabled && !alternate) {
  32337. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32338. if (!effect || !scene.activeCamera) {
  32339. return this;
  32340. }
  32341. scene._switchToAlternateCameraConfiguration(true);
  32342. this._effectiveMaterial.bindView(effect);
  32343. this._effectiveMaterial.bindViewProjection(effect);
  32344. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32345. this._draw(subMesh, fillMode, instancesCount, true);
  32346. engine.setViewport(scene.activeCamera.viewport);
  32347. scene._switchToAlternateCameraConfiguration(false);
  32348. this._effectiveMaterial.bindView(effect);
  32349. this._effectiveMaterial.bindViewProjection(effect);
  32350. }
  32351. return this;
  32352. };
  32353. /**
  32354. * Registers for this mesh a javascript function called just before the rendering process.
  32355. * This function is passed the current mesh.
  32356. * Return the Mesh.
  32357. */
  32358. Mesh.prototype.registerBeforeRender = function (func) {
  32359. this.onBeforeRenderObservable.add(func);
  32360. return this;
  32361. };
  32362. /**
  32363. * Disposes a previously registered javascript function called before the rendering.
  32364. * This function is passed the current mesh.
  32365. * Returns the Mesh.
  32366. */
  32367. Mesh.prototype.unregisterBeforeRender = function (func) {
  32368. this.onBeforeRenderObservable.removeCallback(func);
  32369. return this;
  32370. };
  32371. /**
  32372. * Registers for this mesh a javascript function called just after the rendering is complete.
  32373. * This function is passed the current mesh.
  32374. * Returns the Mesh.
  32375. */
  32376. Mesh.prototype.registerAfterRender = function (func) {
  32377. this.onAfterRenderObservable.add(func);
  32378. return this;
  32379. };
  32380. /**
  32381. * Disposes a previously registered javascript function called after the rendering.
  32382. * This function is passed the current mesh.
  32383. * Return the Mesh.
  32384. */
  32385. Mesh.prototype.unregisterAfterRender = function (func) {
  32386. this.onAfterRenderObservable.removeCallback(func);
  32387. return this;
  32388. };
  32389. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32390. var scene = this.getScene();
  32391. this._batchCache.mustReturn = false;
  32392. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32393. this._batchCache.visibleInstances[subMeshId] = null;
  32394. if (this._visibleInstances) {
  32395. var currentRenderId = scene.getRenderId();
  32396. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32397. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32398. var selfRenderId = this._renderId;
  32399. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32400. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32401. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32402. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32403. }
  32404. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32405. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32406. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32407. this._batchCache.mustReturn = true;
  32408. return this._batchCache;
  32409. }
  32410. if (currentRenderId !== selfRenderId) {
  32411. this._batchCache.renderSelf[subMeshId] = false;
  32412. }
  32413. }
  32414. this._renderIdForInstances[subMeshId] = currentRenderId;
  32415. }
  32416. return this._batchCache;
  32417. };
  32418. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32419. var visibleInstances = batch.visibleInstances[subMesh._id];
  32420. if (!visibleInstances) {
  32421. return this;
  32422. }
  32423. var matricesCount = visibleInstances.length + 1;
  32424. var bufferSize = matricesCount * 16 * 4;
  32425. var currentInstancesBufferSize = this._instancesBufferSize;
  32426. var instancesBuffer = this._instancesBuffer;
  32427. while (this._instancesBufferSize < bufferSize) {
  32428. this._instancesBufferSize *= 2;
  32429. }
  32430. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32431. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32432. }
  32433. var offset = 0;
  32434. var instancesCount = 0;
  32435. var world = this.getWorldMatrix();
  32436. if (batch.renderSelf[subMesh._id]) {
  32437. world.copyToArray(this._instancesData, offset);
  32438. offset += 16;
  32439. instancesCount++;
  32440. }
  32441. if (visibleInstances) {
  32442. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32443. var instance = visibleInstances[instanceIndex];
  32444. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32445. offset += 16;
  32446. instancesCount++;
  32447. }
  32448. }
  32449. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32450. if (instancesBuffer) {
  32451. instancesBuffer.dispose();
  32452. }
  32453. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32454. this._instancesBuffer = instancesBuffer;
  32455. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32456. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32457. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32458. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32459. }
  32460. else {
  32461. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32462. }
  32463. this._bind(subMesh, effect, fillMode);
  32464. this._draw(subMesh, fillMode, instancesCount);
  32465. engine.unbindInstanceAttributes();
  32466. return this;
  32467. };
  32468. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32469. var scene = this.getScene();
  32470. var engine = scene.getEngine();
  32471. if (hardwareInstancedRendering) {
  32472. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32473. }
  32474. else {
  32475. if (batch.renderSelf[subMesh._id]) {
  32476. // Draw
  32477. if (onBeforeDraw) {
  32478. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32479. }
  32480. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32481. }
  32482. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32483. if (visibleInstancesForSubMesh) {
  32484. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32485. var instance = visibleInstancesForSubMesh[instanceIndex];
  32486. // World
  32487. var world = instance.getWorldMatrix();
  32488. if (onBeforeDraw) {
  32489. onBeforeDraw(true, world, effectiveMaterial);
  32490. }
  32491. // Draw
  32492. this._draw(subMesh, fillMode);
  32493. }
  32494. }
  32495. }
  32496. return this;
  32497. };
  32498. /**
  32499. * Triggers the draw call for the mesh.
  32500. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32501. * Returns the Mesh.
  32502. */
  32503. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32504. this._checkOcclusionQuery();
  32505. if (this._isOccluded) {
  32506. return this;
  32507. }
  32508. var scene = this.getScene();
  32509. // Managing instances
  32510. var batch = this._getInstancesRenderList(subMesh._id);
  32511. if (batch.mustReturn) {
  32512. return this;
  32513. }
  32514. // Checking geometry state
  32515. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32516. return this;
  32517. }
  32518. this.onBeforeRenderObservable.notifyObservers(this);
  32519. var engine = scene.getEngine();
  32520. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32521. // Material
  32522. var material = subMesh.getMaterial();
  32523. if (!material) {
  32524. return this;
  32525. }
  32526. this._effectiveMaterial = material;
  32527. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32528. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32529. return this;
  32530. }
  32531. }
  32532. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32533. return this;
  32534. }
  32535. // Alpha mode
  32536. if (enableAlphaMode) {
  32537. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32538. }
  32539. // Outline - step 1
  32540. var savedDepthWrite = engine.getDepthWrite();
  32541. if (this.renderOutline) {
  32542. engine.setDepthWrite(false);
  32543. scene.getOutlineRenderer().render(subMesh, batch);
  32544. engine.setDepthWrite(savedDepthWrite);
  32545. }
  32546. var effect;
  32547. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32548. effect = subMesh.effect;
  32549. }
  32550. else {
  32551. effect = this._effectiveMaterial.getEffect();
  32552. }
  32553. if (!effect) {
  32554. return this;
  32555. }
  32556. var sideOrientation = this.overrideMaterialSideOrientation;
  32557. if (sideOrientation == null) {
  32558. sideOrientation = this._effectiveMaterial.sideOrientation;
  32559. if (this._getWorldMatrixDeterminant() < 0) {
  32560. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32561. }
  32562. }
  32563. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32564. if (this._effectiveMaterial.forceDepthWrite) {
  32565. engine.setDepthWrite(true);
  32566. }
  32567. // Bind
  32568. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32569. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32570. this._bind(subMesh, effect, fillMode);
  32571. }
  32572. var world = this.getWorldMatrix();
  32573. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32574. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32575. }
  32576. else {
  32577. this._effectiveMaterial.bind(world, this);
  32578. }
  32579. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32580. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32581. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32582. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32583. }
  32584. // Draw
  32585. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32586. // Unbind
  32587. this._effectiveMaterial.unbind();
  32588. // Outline - step 2
  32589. if (this.renderOutline && savedDepthWrite) {
  32590. engine.setDepthWrite(true);
  32591. engine.setColorWrite(false);
  32592. scene.getOutlineRenderer().render(subMesh, batch);
  32593. engine.setColorWrite(true);
  32594. }
  32595. // Overlay
  32596. if (this.renderOverlay) {
  32597. var currentMode = engine.getAlphaMode();
  32598. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32599. scene.getOutlineRenderer().render(subMesh, batch, true);
  32600. engine.setAlphaMode(currentMode);
  32601. }
  32602. this.onAfterRenderObservable.notifyObservers(this);
  32603. return this;
  32604. };
  32605. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32606. if (isInstance && effectiveMaterial) {
  32607. effectiveMaterial.bindOnlyWorldMatrix(world);
  32608. }
  32609. };
  32610. /**
  32611. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32612. */
  32613. Mesh.prototype.getEmittedParticleSystems = function () {
  32614. var results = new Array();
  32615. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32616. var particleSystem = this.getScene().particleSystems[index];
  32617. if (particleSystem.emitter === this) {
  32618. results.push(particleSystem);
  32619. }
  32620. }
  32621. return results;
  32622. };
  32623. /**
  32624. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32625. */
  32626. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32627. var results = new Array();
  32628. var descendants = this.getDescendants();
  32629. descendants.push(this);
  32630. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32631. var particleSystem = this.getScene().particleSystems[index];
  32632. var emitter = particleSystem.emitter;
  32633. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32634. results.push(particleSystem);
  32635. }
  32636. }
  32637. return results;
  32638. };
  32639. /**
  32640. * Normalize matrix weights so that all vertices have a total weight set to 1
  32641. */
  32642. Mesh.prototype.cleanMatrixWeights = function () {
  32643. var epsilon = 1e-3;
  32644. var noInfluenceBoneIndex = 0.0;
  32645. if (this.skeleton) {
  32646. noInfluenceBoneIndex = this.skeleton.bones.length;
  32647. }
  32648. else {
  32649. return;
  32650. }
  32651. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32652. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32653. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32654. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32655. var influencers = this.numBoneInfluencers;
  32656. var size = matricesWeights.length;
  32657. for (var i = 0; i < size; i += 4) {
  32658. var weight = 0.0;
  32659. var firstZeroWeight = -1;
  32660. for (var j = 0; j < 4; j++) {
  32661. var w = matricesWeights[i + j];
  32662. weight += w;
  32663. if (w < epsilon && firstZeroWeight < 0) {
  32664. firstZeroWeight = j;
  32665. }
  32666. }
  32667. if (matricesWeightsExtra) {
  32668. for (var j = 0; j < 4; j++) {
  32669. var w = matricesWeightsExtra[i + j];
  32670. weight += w;
  32671. if (w < epsilon && firstZeroWeight < 0) {
  32672. firstZeroWeight = j + 4;
  32673. }
  32674. }
  32675. }
  32676. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32677. firstZeroWeight = influencers - 1;
  32678. }
  32679. if (weight > epsilon) {
  32680. var mweight = 1.0 / weight;
  32681. for (var j = 0; j < 4; j++) {
  32682. matricesWeights[i + j] *= mweight;
  32683. }
  32684. if (matricesWeightsExtra) {
  32685. for (var j = 0; j < 4; j++) {
  32686. matricesWeightsExtra[i + j] *= mweight;
  32687. }
  32688. }
  32689. }
  32690. else {
  32691. if (firstZeroWeight >= 4) {
  32692. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32693. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32694. }
  32695. else {
  32696. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32697. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32698. }
  32699. }
  32700. }
  32701. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32702. if (matricesIndicesExtra) {
  32703. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32704. }
  32705. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32706. if (matricesWeightsExtra) {
  32707. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32708. }
  32709. };
  32710. Mesh.prototype._checkDelayState = function () {
  32711. var scene = this.getScene();
  32712. if (this._geometry) {
  32713. this._geometry.load(scene);
  32714. }
  32715. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32716. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32717. this._queueLoad(scene);
  32718. }
  32719. return this;
  32720. };
  32721. Mesh.prototype._queueLoad = function (scene) {
  32722. var _this = this;
  32723. scene._addPendingData(this);
  32724. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32725. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32726. if (data instanceof ArrayBuffer) {
  32727. _this._delayLoadingFunction(data, _this);
  32728. }
  32729. else {
  32730. _this._delayLoadingFunction(JSON.parse(data), _this);
  32731. }
  32732. _this.instances.forEach(function (instance) {
  32733. instance._syncSubMeshes();
  32734. });
  32735. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32736. scene._removePendingData(_this);
  32737. }, function () { }, scene.database, getBinaryData);
  32738. return this;
  32739. };
  32740. /**
  32741. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32742. */
  32743. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32744. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32745. return false;
  32746. }
  32747. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32748. return false;
  32749. }
  32750. this._checkDelayState();
  32751. return true;
  32752. };
  32753. /**
  32754. * Sets the mesh material by the material or multiMaterial `id` property.
  32755. * The material `id` is a string identifying the material or the multiMaterial.
  32756. * This method returns the Mesh.
  32757. */
  32758. Mesh.prototype.setMaterialByID = function (id) {
  32759. var materials = this.getScene().materials;
  32760. var index;
  32761. for (index = materials.length - 1; index > -1; index--) {
  32762. if (materials[index].id === id) {
  32763. this.material = materials[index];
  32764. return this;
  32765. }
  32766. }
  32767. // Multi
  32768. var multiMaterials = this.getScene().multiMaterials;
  32769. for (index = multiMaterials.length - 1; index > -1; index--) {
  32770. if (multiMaterials[index].id === id) {
  32771. this.material = multiMaterials[index];
  32772. return this;
  32773. }
  32774. }
  32775. return this;
  32776. };
  32777. /**
  32778. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32779. */
  32780. Mesh.prototype.getAnimatables = function () {
  32781. var results = new Array();
  32782. if (this.material) {
  32783. results.push(this.material);
  32784. }
  32785. if (this.skeleton) {
  32786. results.push(this.skeleton);
  32787. }
  32788. return results;
  32789. };
  32790. /**
  32791. * Modifies the mesh geometry according to the passed transformation matrix.
  32792. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32793. * The mesh normals are modified accordingly the same transformation.
  32794. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32795. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32796. * Returns the Mesh.
  32797. */
  32798. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32799. // Position
  32800. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32801. return this;
  32802. }
  32803. var submeshes = this.subMeshes.splice(0);
  32804. this._resetPointsArrayCache();
  32805. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32806. var temp = new Array();
  32807. var index;
  32808. for (index = 0; index < data.length; index += 3) {
  32809. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32810. }
  32811. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32812. // Normals
  32813. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32814. return this;
  32815. }
  32816. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32817. temp = [];
  32818. for (index = 0; index < data.length; index += 3) {
  32819. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32820. }
  32821. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32822. // flip faces?
  32823. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32824. this.flipFaces();
  32825. }
  32826. // Restore submeshes
  32827. this.releaseSubMeshes();
  32828. this.subMeshes = submeshes;
  32829. return this;
  32830. };
  32831. /**
  32832. * Modifies the mesh geometry according to its own current World Matrix.
  32833. * The mesh World Matrix is then reset.
  32834. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32835. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32836. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32837. * Returns the Mesh.
  32838. */
  32839. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32840. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32841. this.scaling.copyFromFloats(1, 1, 1);
  32842. this.position.copyFromFloats(0, 0, 0);
  32843. this.rotation.copyFromFloats(0, 0, 0);
  32844. //only if quaternion is already set
  32845. if (this.rotationQuaternion) {
  32846. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32847. }
  32848. this._worldMatrix = BABYLON.Matrix.Identity();
  32849. return this;
  32850. };
  32851. Object.defineProperty(Mesh.prototype, "_positions", {
  32852. // Cache
  32853. get: function () {
  32854. if (this._geometry) {
  32855. return this._geometry._positions;
  32856. }
  32857. return null;
  32858. },
  32859. enumerable: true,
  32860. configurable: true
  32861. });
  32862. Mesh.prototype._resetPointsArrayCache = function () {
  32863. if (this._geometry) {
  32864. this._geometry._resetPointsArrayCache();
  32865. }
  32866. return this;
  32867. };
  32868. Mesh.prototype._generatePointsArray = function () {
  32869. if (this._geometry) {
  32870. return this._geometry._generatePointsArray();
  32871. }
  32872. return false;
  32873. };
  32874. /**
  32875. * Returns a new Mesh object generated from the current mesh properties.
  32876. * This method must not get confused with createInstance().
  32877. * The parameter `name` is a string, the name given to the new mesh.
  32878. * The optional parameter `newParent` can be any Node object (default `null`).
  32879. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32880. * 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.
  32881. */
  32882. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32883. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32884. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32885. };
  32886. /**
  32887. * Releases resources associated with this mesh.
  32888. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32889. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32890. */
  32891. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32892. var _this = this;
  32893. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32894. this.morphTargetManager = null;
  32895. if (this._geometry) {
  32896. this._geometry.releaseForMesh(this, true);
  32897. }
  32898. // Sources
  32899. var meshes = this.getScene().meshes;
  32900. meshes.forEach(function (abstractMesh) {
  32901. var mesh = abstractMesh;
  32902. if (mesh._source && mesh._source === _this) {
  32903. mesh._source = null;
  32904. }
  32905. });
  32906. this._source = null;
  32907. // Instances
  32908. if (this._instancesBuffer) {
  32909. this._instancesBuffer.dispose();
  32910. this._instancesBuffer = null;
  32911. }
  32912. while (this.instances.length) {
  32913. this.instances[0].dispose();
  32914. }
  32915. // Effect layers.
  32916. var effectLayers = this.getScene().effectLayers;
  32917. for (var i = 0; i < effectLayers.length; i++) {
  32918. var effectLayer = effectLayers[i];
  32919. if (effectLayer) {
  32920. effectLayer._disposeMesh(this);
  32921. }
  32922. }
  32923. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32924. };
  32925. /**
  32926. * Modifies the mesh geometry according to a displacement map.
  32927. * 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.
  32928. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32929. * This method returns nothing.
  32930. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32931. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32932. * 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.
  32933. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32934. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32935. *
  32936. * Returns the Mesh.
  32937. */
  32938. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32939. var _this = this;
  32940. var scene = this.getScene();
  32941. var onload = function (img) {
  32942. // Getting height map data
  32943. var canvas = document.createElement("canvas");
  32944. var context = canvas.getContext("2d");
  32945. var heightMapWidth = img.width;
  32946. var heightMapHeight = img.height;
  32947. canvas.width = heightMapWidth;
  32948. canvas.height = heightMapHeight;
  32949. context.drawImage(img, 0, 0);
  32950. // Create VertexData from map data
  32951. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32952. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32953. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32954. //execute success callback, if set
  32955. if (onSuccess) {
  32956. onSuccess(_this);
  32957. }
  32958. };
  32959. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32960. return this;
  32961. };
  32962. /**
  32963. * Modifies the mesh geometry according to a displacementMap buffer.
  32964. * 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.
  32965. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32966. * This method returns nothing.
  32967. * 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.
  32968. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32969. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32970. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32971. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32972. *
  32973. * Returns the Mesh.
  32974. */
  32975. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32976. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32977. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32978. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32979. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32980. return this;
  32981. }
  32982. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32983. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32984. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32985. var position = BABYLON.Vector3.Zero();
  32986. var normal = BABYLON.Vector3.Zero();
  32987. var uv = BABYLON.Vector2.Zero();
  32988. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32989. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32990. for (var index = 0; index < positions.length; index += 3) {
  32991. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32992. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32993. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32994. // Compute height
  32995. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32996. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32997. var pos = (u + v * heightMapWidth) * 4;
  32998. var r = buffer[pos] / 255.0;
  32999. var g = buffer[pos + 1] / 255.0;
  33000. var b = buffer[pos + 2] / 255.0;
  33001. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33002. normal.normalize();
  33003. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33004. position = position.add(normal);
  33005. position.toArray(positions, index);
  33006. }
  33007. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33008. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33009. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33010. return this;
  33011. };
  33012. /**
  33013. * Modify the mesh to get a flat shading rendering.
  33014. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33015. * This method returns the Mesh.
  33016. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33017. */
  33018. Mesh.prototype.convertToFlatShadedMesh = function () {
  33019. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33020. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33021. var kinds = this.getVerticesDataKinds();
  33022. var vbs = {};
  33023. var data = {};
  33024. var newdata = {};
  33025. var updatableNormals = false;
  33026. var kindIndex;
  33027. var kind;
  33028. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33029. kind = kinds[kindIndex];
  33030. var vertexBuffer = this.getVertexBuffer(kind);
  33031. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33032. updatableNormals = vertexBuffer.isUpdatable();
  33033. kinds.splice(kindIndex, 1);
  33034. kindIndex--;
  33035. continue;
  33036. }
  33037. vbs[kind] = vertexBuffer;
  33038. data[kind] = vbs[kind].getData();
  33039. newdata[kind] = [];
  33040. }
  33041. // Save previous submeshes
  33042. var previousSubmeshes = this.subMeshes.slice(0);
  33043. var indices = this.getIndices();
  33044. var totalIndices = this.getTotalIndices();
  33045. // Generating unique vertices per face
  33046. var index;
  33047. for (index = 0; index < totalIndices; index++) {
  33048. var vertexIndex = indices[index];
  33049. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33050. kind = kinds[kindIndex];
  33051. var stride = vbs[kind].getStrideSize();
  33052. for (var offset = 0; offset < stride; offset++) {
  33053. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33054. }
  33055. }
  33056. }
  33057. // Updating faces & normal
  33058. var normals = [];
  33059. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33060. for (index = 0; index < totalIndices; index += 3) {
  33061. indices[index] = index;
  33062. indices[index + 1] = index + 1;
  33063. indices[index + 2] = index + 2;
  33064. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33065. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33066. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33067. var p1p2 = p1.subtract(p2);
  33068. var p3p2 = p3.subtract(p2);
  33069. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33070. // Store same normals for every vertex
  33071. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33072. normals.push(normal.x);
  33073. normals.push(normal.y);
  33074. normals.push(normal.z);
  33075. }
  33076. }
  33077. this.setIndices(indices);
  33078. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33079. // Updating vertex buffers
  33080. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33081. kind = kinds[kindIndex];
  33082. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33083. }
  33084. // Updating submeshes
  33085. this.releaseSubMeshes();
  33086. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33087. var previousOne = previousSubmeshes[submeshIndex];
  33088. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33089. }
  33090. this.synchronizeInstances();
  33091. return this;
  33092. };
  33093. /**
  33094. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33095. * In other words, more vertices, no more indices and a single bigger VBO.
  33096. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33097. * Returns the Mesh.
  33098. */
  33099. Mesh.prototype.convertToUnIndexedMesh = function () {
  33100. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33101. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33102. var kinds = this.getVerticesDataKinds();
  33103. var vbs = {};
  33104. var data = {};
  33105. var newdata = {};
  33106. var kindIndex;
  33107. var kind;
  33108. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33109. kind = kinds[kindIndex];
  33110. var vertexBuffer = this.getVertexBuffer(kind);
  33111. vbs[kind] = vertexBuffer;
  33112. data[kind] = vbs[kind].getData();
  33113. newdata[kind] = [];
  33114. }
  33115. // Save previous submeshes
  33116. var previousSubmeshes = this.subMeshes.slice(0);
  33117. var indices = this.getIndices();
  33118. var totalIndices = this.getTotalIndices();
  33119. // Generating unique vertices per face
  33120. var index;
  33121. for (index = 0; index < totalIndices; index++) {
  33122. var vertexIndex = indices[index];
  33123. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33124. kind = kinds[kindIndex];
  33125. var stride = vbs[kind].getStrideSize();
  33126. for (var offset = 0; offset < stride; offset++) {
  33127. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33128. }
  33129. }
  33130. }
  33131. // Updating indices
  33132. for (index = 0; index < totalIndices; index += 3) {
  33133. indices[index] = index;
  33134. indices[index + 1] = index + 1;
  33135. indices[index + 2] = index + 2;
  33136. }
  33137. this.setIndices(indices);
  33138. // Updating vertex buffers
  33139. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33140. kind = kinds[kindIndex];
  33141. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33142. }
  33143. // Updating submeshes
  33144. this.releaseSubMeshes();
  33145. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33146. var previousOne = previousSubmeshes[submeshIndex];
  33147. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33148. }
  33149. this._unIndexed = true;
  33150. this.synchronizeInstances();
  33151. return this;
  33152. };
  33153. /**
  33154. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33155. * This method returns the Mesh.
  33156. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33157. */
  33158. Mesh.prototype.flipFaces = function (flipNormals) {
  33159. if (flipNormals === void 0) { flipNormals = false; }
  33160. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33161. var i;
  33162. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33163. for (i = 0; i < vertex_data.normals.length; i++) {
  33164. vertex_data.normals[i] *= -1;
  33165. }
  33166. }
  33167. if (vertex_data.indices) {
  33168. var temp;
  33169. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33170. // reassign indices
  33171. temp = vertex_data.indices[i + 1];
  33172. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33173. vertex_data.indices[i + 2] = temp;
  33174. }
  33175. }
  33176. vertex_data.applyToMesh(this);
  33177. return this;
  33178. };
  33179. // Instances
  33180. /**
  33181. * Creates a new InstancedMesh object from the mesh model.
  33182. * An instance shares the same properties and the same material than its model.
  33183. * Only these properties of each instance can then be set individually :
  33184. * - position
  33185. * - rotation
  33186. * - rotationQuaternion
  33187. * - setPivotMatrix
  33188. * - scaling
  33189. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33190. * Warning : this method is not supported for Line mesh and LineSystem
  33191. */
  33192. Mesh.prototype.createInstance = function (name) {
  33193. return new BABYLON.InstancedMesh(name, this);
  33194. };
  33195. /**
  33196. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33197. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33198. * This method returns the Mesh.
  33199. */
  33200. Mesh.prototype.synchronizeInstances = function () {
  33201. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33202. var instance = this.instances[instanceIndex];
  33203. instance._syncSubMeshes();
  33204. }
  33205. return this;
  33206. };
  33207. /**
  33208. * Simplify the mesh according to the given array of settings.
  33209. * Function will return immediately and will simplify async. It returns the Mesh.
  33210. * @param settings a collection of simplification settings.
  33211. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33212. * @param type the type of simplification to run.
  33213. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33214. */
  33215. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33216. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33217. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33218. this.getScene().simplificationQueue.addTask({
  33219. settings: settings,
  33220. parallelProcessing: parallelProcessing,
  33221. mesh: this,
  33222. simplificationType: simplificationType,
  33223. successCallback: successCallback
  33224. });
  33225. return this;
  33226. };
  33227. /**
  33228. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33229. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33230. * This should be used together with the simplification to avoid disappearing triangles.
  33231. * Returns the Mesh.
  33232. * @param successCallback an optional success callback to be called after the optimization finished.
  33233. */
  33234. Mesh.prototype.optimizeIndices = function (successCallback) {
  33235. var _this = this;
  33236. var indices = this.getIndices();
  33237. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33238. if (!positions || !indices) {
  33239. return this;
  33240. }
  33241. var vectorPositions = new Array();
  33242. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33243. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33244. }
  33245. var dupes = new Array();
  33246. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33247. var realPos = vectorPositions.length - 1 - iteration;
  33248. var testedPosition = vectorPositions[realPos];
  33249. for (var j = 0; j < realPos; ++j) {
  33250. var againstPosition = vectorPositions[j];
  33251. if (testedPosition.equals(againstPosition)) {
  33252. dupes[realPos] = j;
  33253. break;
  33254. }
  33255. }
  33256. }, function () {
  33257. for (var i = 0; i < indices.length; ++i) {
  33258. indices[i] = dupes[indices[i]] || indices[i];
  33259. }
  33260. //indices are now reordered
  33261. var originalSubMeshes = _this.subMeshes.slice(0);
  33262. _this.setIndices(indices);
  33263. _this.subMeshes = originalSubMeshes;
  33264. if (successCallback) {
  33265. successCallback(_this);
  33266. }
  33267. });
  33268. return this;
  33269. };
  33270. Mesh.prototype.serialize = function (serializationObject) {
  33271. serializationObject.name = this.name;
  33272. serializationObject.id = this.id;
  33273. serializationObject.type = this.getClassName();
  33274. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33275. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33276. }
  33277. serializationObject.position = this.position.asArray();
  33278. if (this.rotationQuaternion) {
  33279. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33280. }
  33281. else if (this.rotation) {
  33282. serializationObject.rotation = this.rotation.asArray();
  33283. }
  33284. serializationObject.scaling = this.scaling.asArray();
  33285. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33286. serializationObject.isEnabled = this.isEnabled(false);
  33287. serializationObject.isVisible = this.isVisible;
  33288. serializationObject.infiniteDistance = this.infiniteDistance;
  33289. serializationObject.pickable = this.isPickable;
  33290. serializationObject.receiveShadows = this.receiveShadows;
  33291. serializationObject.billboardMode = this.billboardMode;
  33292. serializationObject.visibility = this.visibility;
  33293. serializationObject.checkCollisions = this.checkCollisions;
  33294. serializationObject.isBlocker = this.isBlocker;
  33295. // Parent
  33296. if (this.parent) {
  33297. serializationObject.parentId = this.parent.id;
  33298. }
  33299. // Geometry
  33300. serializationObject.isUnIndexed = this.isUnIndexed;
  33301. var geometry = this._geometry;
  33302. if (geometry) {
  33303. var geometryId = geometry.id;
  33304. serializationObject.geometryId = geometryId;
  33305. // SubMeshes
  33306. serializationObject.subMeshes = [];
  33307. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33308. var subMesh = this.subMeshes[subIndex];
  33309. serializationObject.subMeshes.push({
  33310. materialIndex: subMesh.materialIndex,
  33311. verticesStart: subMesh.verticesStart,
  33312. verticesCount: subMesh.verticesCount,
  33313. indexStart: subMesh.indexStart,
  33314. indexCount: subMesh.indexCount
  33315. });
  33316. }
  33317. }
  33318. // Material
  33319. if (this.material) {
  33320. serializationObject.materialId = this.material.id;
  33321. }
  33322. else {
  33323. this.material = null;
  33324. }
  33325. // Morph targets
  33326. if (this.morphTargetManager) {
  33327. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33328. }
  33329. // Skeleton
  33330. if (this.skeleton) {
  33331. serializationObject.skeletonId = this.skeleton.id;
  33332. }
  33333. // Physics
  33334. //TODO implement correct serialization for physics impostors.
  33335. var impostor = this.getPhysicsImpostor();
  33336. if (impostor) {
  33337. serializationObject.physicsMass = impostor.getParam("mass");
  33338. serializationObject.physicsFriction = impostor.getParam("friction");
  33339. serializationObject.physicsRestitution = impostor.getParam("mass");
  33340. serializationObject.physicsImpostor = impostor.type;
  33341. }
  33342. // Metadata
  33343. if (this.metadata) {
  33344. serializationObject.metadata = this.metadata;
  33345. }
  33346. // Instances
  33347. serializationObject.instances = [];
  33348. for (var index = 0; index < this.instances.length; index++) {
  33349. var instance = this.instances[index];
  33350. var serializationInstance = {
  33351. name: instance.name,
  33352. id: instance.id,
  33353. position: instance.position.asArray(),
  33354. scaling: instance.scaling.asArray()
  33355. };
  33356. if (instance.rotationQuaternion) {
  33357. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33358. }
  33359. else if (instance.rotation) {
  33360. serializationInstance.rotation = instance.rotation.asArray();
  33361. }
  33362. serializationObject.instances.push(serializationInstance);
  33363. // Animations
  33364. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33365. serializationInstance.ranges = instance.serializeAnimationRanges();
  33366. }
  33367. //
  33368. // Animations
  33369. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33370. serializationObject.ranges = this.serializeAnimationRanges();
  33371. // Layer mask
  33372. serializationObject.layerMask = this.layerMask;
  33373. // Alpha
  33374. serializationObject.alphaIndex = this.alphaIndex;
  33375. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33376. // Overlay
  33377. serializationObject.overlayAlpha = this.overlayAlpha;
  33378. serializationObject.overlayColor = this.overlayColor.asArray();
  33379. serializationObject.renderOverlay = this.renderOverlay;
  33380. // Fog
  33381. serializationObject.applyFog = this.applyFog;
  33382. // Action Manager
  33383. if (this.actionManager) {
  33384. serializationObject.actions = this.actionManager.serialize(this.name);
  33385. }
  33386. };
  33387. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33388. if (!this.geometry) {
  33389. return;
  33390. }
  33391. this._markSubMeshesAsAttributesDirty();
  33392. var morphTargetManager = this._morphTargetManager;
  33393. if (morphTargetManager && morphTargetManager.vertexCount) {
  33394. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33395. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33396. this.morphTargetManager = null;
  33397. return;
  33398. }
  33399. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33400. var morphTarget = morphTargetManager.getActiveTarget(index);
  33401. var positions = morphTarget.getPositions();
  33402. if (!positions) {
  33403. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33404. return;
  33405. }
  33406. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33407. var normals = morphTarget.getNormals();
  33408. if (normals) {
  33409. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33410. }
  33411. var tangents = morphTarget.getTangents();
  33412. if (tangents) {
  33413. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33414. }
  33415. }
  33416. }
  33417. else {
  33418. var index = 0;
  33419. // Positions
  33420. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33421. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33422. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33423. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33424. }
  33425. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33426. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33427. }
  33428. index++;
  33429. }
  33430. }
  33431. };
  33432. // Statics
  33433. /**
  33434. * Returns a new Mesh object parsed from the source provided.
  33435. * The parameter `parsedMesh` is the source.
  33436. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33437. */
  33438. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33439. var mesh;
  33440. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33441. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33442. }
  33443. else {
  33444. mesh = new Mesh(parsedMesh.name, scene);
  33445. }
  33446. mesh.id = parsedMesh.id;
  33447. if (BABYLON.Tags) {
  33448. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33449. }
  33450. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33451. if (parsedMesh.metadata !== undefined) {
  33452. mesh.metadata = parsedMesh.metadata;
  33453. }
  33454. if (parsedMesh.rotationQuaternion) {
  33455. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33456. }
  33457. else if (parsedMesh.rotation) {
  33458. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33459. }
  33460. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33461. if (parsedMesh.localMatrix) {
  33462. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33463. }
  33464. else if (parsedMesh.pivotMatrix) {
  33465. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33466. }
  33467. mesh.setEnabled(parsedMesh.isEnabled);
  33468. mesh.isVisible = parsedMesh.isVisible;
  33469. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33470. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33471. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33472. if (parsedMesh.applyFog !== undefined) {
  33473. mesh.applyFog = parsedMesh.applyFog;
  33474. }
  33475. if (parsedMesh.pickable !== undefined) {
  33476. mesh.isPickable = parsedMesh.pickable;
  33477. }
  33478. if (parsedMesh.alphaIndex !== undefined) {
  33479. mesh.alphaIndex = parsedMesh.alphaIndex;
  33480. }
  33481. mesh.receiveShadows = parsedMesh.receiveShadows;
  33482. mesh.billboardMode = parsedMesh.billboardMode;
  33483. if (parsedMesh.visibility !== undefined) {
  33484. mesh.visibility = parsedMesh.visibility;
  33485. }
  33486. mesh.checkCollisions = parsedMesh.checkCollisions;
  33487. if (parsedMesh.isBlocker !== undefined) {
  33488. mesh.isBlocker = parsedMesh.isBlocker;
  33489. }
  33490. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33491. // freezeWorldMatrix
  33492. if (parsedMesh.freezeWorldMatrix) {
  33493. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33494. }
  33495. // Parent
  33496. if (parsedMesh.parentId) {
  33497. mesh._waitingParentId = parsedMesh.parentId;
  33498. }
  33499. // Actions
  33500. if (parsedMesh.actions !== undefined) {
  33501. mesh._waitingActions = parsedMesh.actions;
  33502. }
  33503. // Overlay
  33504. if (parsedMesh.overlayAlpha !== undefined) {
  33505. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33506. }
  33507. if (parsedMesh.overlayColor !== undefined) {
  33508. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33509. }
  33510. if (parsedMesh.renderOverlay !== undefined) {
  33511. mesh.renderOverlay = parsedMesh.renderOverlay;
  33512. }
  33513. // Geometry
  33514. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33515. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33516. if (parsedMesh.delayLoadingFile) {
  33517. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33518. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33519. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33520. if (parsedMesh._binaryInfo) {
  33521. mesh._binaryInfo = parsedMesh._binaryInfo;
  33522. }
  33523. mesh._delayInfo = [];
  33524. if (parsedMesh.hasUVs) {
  33525. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33526. }
  33527. if (parsedMesh.hasUVs2) {
  33528. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33529. }
  33530. if (parsedMesh.hasUVs3) {
  33531. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33532. }
  33533. if (parsedMesh.hasUVs4) {
  33534. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33535. }
  33536. if (parsedMesh.hasUVs5) {
  33537. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33538. }
  33539. if (parsedMesh.hasUVs6) {
  33540. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33541. }
  33542. if (parsedMesh.hasColors) {
  33543. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33544. }
  33545. if (parsedMesh.hasMatricesIndices) {
  33546. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33547. }
  33548. if (parsedMesh.hasMatricesWeights) {
  33549. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33550. }
  33551. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33552. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33553. mesh._checkDelayState();
  33554. }
  33555. }
  33556. else {
  33557. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33558. }
  33559. // Material
  33560. if (parsedMesh.materialId) {
  33561. mesh.setMaterialByID(parsedMesh.materialId);
  33562. }
  33563. else {
  33564. mesh.material = null;
  33565. }
  33566. // Morph targets
  33567. if (parsedMesh.morphTargetManagerId > -1) {
  33568. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33569. }
  33570. // Skeleton
  33571. if (parsedMesh.skeletonId > -1) {
  33572. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33573. if (parsedMesh.numBoneInfluencers) {
  33574. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33575. }
  33576. }
  33577. // Animations
  33578. if (parsedMesh.animations) {
  33579. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33580. var parsedAnimation = parsedMesh.animations[animationIndex];
  33581. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33582. }
  33583. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33584. }
  33585. if (parsedMesh.autoAnimate) {
  33586. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33587. }
  33588. // Layer Mask
  33589. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33590. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33591. }
  33592. else {
  33593. mesh.layerMask = 0x0FFFFFFF;
  33594. }
  33595. // Physics
  33596. if (parsedMesh.physicsImpostor) {
  33597. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33598. mass: parsedMesh.physicsMass,
  33599. friction: parsedMesh.physicsFriction,
  33600. restitution: parsedMesh.physicsRestitution
  33601. }, scene);
  33602. }
  33603. // Instances
  33604. if (parsedMesh.instances) {
  33605. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33606. var parsedInstance = parsedMesh.instances[index];
  33607. var instance = mesh.createInstance(parsedInstance.name);
  33608. if (parsedInstance.id) {
  33609. instance.id = parsedInstance.id;
  33610. }
  33611. if (BABYLON.Tags) {
  33612. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33613. }
  33614. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33615. if (parsedInstance.parentId) {
  33616. instance._waitingParentId = parsedInstance.parentId;
  33617. }
  33618. if (parsedInstance.rotationQuaternion) {
  33619. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33620. }
  33621. else if (parsedInstance.rotation) {
  33622. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33623. }
  33624. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33625. instance.checkCollisions = mesh.checkCollisions;
  33626. if (parsedMesh.animations) {
  33627. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33628. parsedAnimation = parsedMesh.animations[animationIndex];
  33629. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33630. }
  33631. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33632. if (parsedMesh.autoAnimate) {
  33633. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33634. }
  33635. }
  33636. }
  33637. }
  33638. return mesh;
  33639. };
  33640. /**
  33641. * Creates a ribbon mesh.
  33642. * Please consider using the same method from the MeshBuilder class instead.
  33643. * 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.
  33644. *
  33645. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33646. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33647. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33648. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33649. * 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.
  33650. * 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.
  33651. * 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
  33652. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33653. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33654. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33655. */
  33656. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33657. if (closeArray === void 0) { closeArray = false; }
  33658. if (updatable === void 0) { updatable = false; }
  33659. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33660. pathArray: pathArray,
  33661. closeArray: closeArray,
  33662. closePath: closePath,
  33663. offset: offset,
  33664. updatable: updatable,
  33665. sideOrientation: sideOrientation,
  33666. instance: instance
  33667. }, scene);
  33668. };
  33669. /**
  33670. * Creates a plane polygonal mesh. By default, this is a disc.
  33671. * Please consider using the same method from the MeshBuilder class instead.
  33672. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33673. * 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.
  33674. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33675. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33677. */
  33678. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33679. if (scene === void 0) { scene = null; }
  33680. var options = {
  33681. radius: radius,
  33682. tessellation: tessellation,
  33683. sideOrientation: sideOrientation,
  33684. updatable: updatable
  33685. };
  33686. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33687. };
  33688. /**
  33689. * Creates a box mesh.
  33690. * Please consider using the same method from the MeshBuilder class instead.
  33691. * The parameter `size` sets the size (float) of each box side (default 1).
  33692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33693. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33695. */
  33696. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33697. if (scene === void 0) { scene = null; }
  33698. var options = {
  33699. size: size,
  33700. sideOrientation: sideOrientation,
  33701. updatable: updatable
  33702. };
  33703. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33704. };
  33705. /**
  33706. * Creates a sphere mesh.
  33707. * Please consider using the same method from the MeshBuilder class instead.
  33708. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33709. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33710. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33711. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33713. */
  33714. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33715. var options = {
  33716. segments: segments,
  33717. diameterX: diameter,
  33718. diameterY: diameter,
  33719. diameterZ: diameter,
  33720. sideOrientation: sideOrientation,
  33721. updatable: updatable
  33722. };
  33723. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33724. };
  33725. /**
  33726. * Creates a cylinder or a cone mesh.
  33727. * Please consider using the same method from the MeshBuilder class instead.
  33728. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33729. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33730. * 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.
  33731. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33732. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33733. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33734. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33735. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33736. */
  33737. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33738. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33739. if (scene !== undefined) {
  33740. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33741. updatable = scene;
  33742. }
  33743. scene = subdivisions;
  33744. subdivisions = 1;
  33745. }
  33746. var options = {
  33747. height: height,
  33748. diameterTop: diameterTop,
  33749. diameterBottom: diameterBottom,
  33750. tessellation: tessellation,
  33751. subdivisions: subdivisions,
  33752. sideOrientation: sideOrientation,
  33753. updatable: updatable
  33754. };
  33755. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33756. };
  33757. // Torus (Code from SharpDX.org)
  33758. /**
  33759. * Creates a torus mesh.
  33760. * Please consider using the same method from the MeshBuilder class instead.
  33761. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33762. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33763. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33764. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33765. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33766. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33767. */
  33768. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33769. var options = {
  33770. diameter: diameter,
  33771. thickness: thickness,
  33772. tessellation: tessellation,
  33773. sideOrientation: sideOrientation,
  33774. updatable: updatable
  33775. };
  33776. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33777. };
  33778. /**
  33779. * Creates a torus knot mesh.
  33780. * Please consider using the same method from the MeshBuilder class instead.
  33781. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33782. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33783. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33784. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33785. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33786. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33788. */
  33789. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33790. var options = {
  33791. radius: radius,
  33792. tube: tube,
  33793. radialSegments: radialSegments,
  33794. tubularSegments: tubularSegments,
  33795. p: p,
  33796. q: q,
  33797. sideOrientation: sideOrientation,
  33798. updatable: updatable
  33799. };
  33800. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33801. };
  33802. /**
  33803. * Creates a line mesh.
  33804. * Please consider using the same method from the MeshBuilder class instead.
  33805. * 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.
  33806. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33807. * The parameter `points` is an array successive Vector3.
  33808. * 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
  33809. * When updating an instance, remember that only point positions can change, not the number of points.
  33810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33811. */
  33812. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33813. if (scene === void 0) { scene = null; }
  33814. if (updatable === void 0) { updatable = false; }
  33815. if (instance === void 0) { instance = null; }
  33816. var options = {
  33817. points: points,
  33818. updatable: updatable,
  33819. instance: instance
  33820. };
  33821. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33822. };
  33823. /**
  33824. * Creates a dashed line mesh.
  33825. * Please consider using the same method from the MeshBuilder class instead.
  33826. * 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.
  33827. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33828. * The parameter `points` is an array successive Vector3.
  33829. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33830. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33831. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33832. * 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
  33833. * When updating an instance, remember that only point positions can change, not the number of points.
  33834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33835. */
  33836. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33837. if (scene === void 0) { scene = null; }
  33838. var options = {
  33839. points: points,
  33840. dashSize: dashSize,
  33841. gapSize: gapSize,
  33842. dashNb: dashNb,
  33843. updatable: updatable,
  33844. instance: instance
  33845. };
  33846. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33847. };
  33848. /**
  33849. * Creates a polygon mesh.
  33850. * Please consider using the same method from the MeshBuilder class instead.
  33851. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33852. * 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.
  33853. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33854. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33855. * Remember you can only change the shape positions, not their number when updating a polygon.
  33856. */
  33857. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33858. var options = {
  33859. shape: shape,
  33860. holes: holes,
  33861. updatable: updatable,
  33862. sideOrientation: sideOrientation
  33863. };
  33864. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33865. };
  33866. /**
  33867. * Creates an extruded polygon mesh, with depth in the Y direction.
  33868. * Please consider using the same method from the MeshBuilder class instead.
  33869. */
  33870. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33871. var options = {
  33872. shape: shape,
  33873. holes: holes,
  33874. depth: depth,
  33875. updatable: updatable,
  33876. sideOrientation: sideOrientation
  33877. };
  33878. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33879. };
  33880. /**
  33881. * Creates an extruded shape mesh.
  33882. * 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.
  33883. * Please consider using the same method from the MeshBuilder class instead.
  33884. *
  33885. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33886. * 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
  33887. * extruded along the Z axis.
  33888. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33889. * 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.
  33890. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33891. * 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
  33892. * 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
  33893. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33894. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33895. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33897. */
  33898. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33899. if (scene === void 0) { scene = null; }
  33900. var options = {
  33901. shape: shape,
  33902. path: path,
  33903. scale: scale,
  33904. rotation: rotation,
  33905. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33906. sideOrientation: sideOrientation,
  33907. instance: instance,
  33908. updatable: updatable
  33909. };
  33910. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33911. };
  33912. /**
  33913. * Creates an custom extruded shape mesh.
  33914. * 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.
  33915. * Please consider using the same method from the MeshBuilder class instead.
  33916. *
  33917. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33918. * 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
  33919. * extruded along the Z axis.
  33920. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33921. * 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
  33922. * and the distance of this point from the begining of the path :
  33923. * ```javascript
  33924. * var rotationFunction = function(i, distance) {
  33925. * // do things
  33926. * return rotationValue; }
  33927. * ```
  33928. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33929. * 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
  33930. * and the distance of this point from the begining of the path :
  33931. * ```javascript
  33932. * var scaleFunction = function(i, distance) {
  33933. * // do things
  33934. * return scaleValue;}
  33935. * ```
  33936. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33937. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33938. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33939. * 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
  33940. * 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
  33941. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33943. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33944. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33945. */
  33946. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33947. var options = {
  33948. shape: shape,
  33949. path: path,
  33950. scaleFunction: scaleFunction,
  33951. rotationFunction: rotationFunction,
  33952. ribbonCloseArray: ribbonCloseArray,
  33953. ribbonClosePath: ribbonClosePath,
  33954. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33955. sideOrientation: sideOrientation,
  33956. instance: instance,
  33957. updatable: updatable
  33958. };
  33959. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33960. };
  33961. /**
  33962. * Creates lathe mesh.
  33963. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33964. * Please consider using the same method from the MeshBuilder class instead.
  33965. * 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
  33966. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33967. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33968. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33969. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33970. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33971. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33972. */
  33973. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33974. var options = {
  33975. shape: shape,
  33976. radius: radius,
  33977. tessellation: tessellation,
  33978. sideOrientation: sideOrientation,
  33979. updatable: updatable
  33980. };
  33981. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33982. };
  33983. /**
  33984. * Creates a plane mesh.
  33985. * Please consider using the same method from the MeshBuilder class instead.
  33986. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33987. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33988. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33989. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33990. */
  33991. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33992. var options = {
  33993. size: size,
  33994. width: size,
  33995. height: size,
  33996. sideOrientation: sideOrientation,
  33997. updatable: updatable
  33998. };
  33999. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34000. };
  34001. /**
  34002. * Creates a ground mesh.
  34003. * Please consider using the same method from the MeshBuilder class instead.
  34004. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34005. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34007. */
  34008. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34009. var options = {
  34010. width: width,
  34011. height: height,
  34012. subdivisions: subdivisions,
  34013. updatable: updatable
  34014. };
  34015. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34016. };
  34017. /**
  34018. * Creates a tiled ground mesh.
  34019. * Please consider using the same method from the MeshBuilder class instead.
  34020. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34021. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34022. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34023. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34024. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34025. * numbers of subdivisions on the ground width and height of each tile.
  34026. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34027. */
  34028. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34029. var options = {
  34030. xmin: xmin,
  34031. zmin: zmin,
  34032. xmax: xmax,
  34033. zmax: zmax,
  34034. subdivisions: subdivisions,
  34035. precision: precision,
  34036. updatable: updatable
  34037. };
  34038. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34039. };
  34040. /**
  34041. * Creates a ground mesh from a height map.
  34042. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34043. * Please consider using the same method from the MeshBuilder class instead.
  34044. * The parameter `url` sets the URL of the height map image resource.
  34045. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34046. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34047. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34048. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34049. * 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).
  34050. * This function is passed the newly built mesh :
  34051. * ```javascript
  34052. * function(mesh) { // do things
  34053. * return; }
  34054. * ```
  34055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34056. */
  34057. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34058. var options = {
  34059. width: width,
  34060. height: height,
  34061. subdivisions: subdivisions,
  34062. minHeight: minHeight,
  34063. maxHeight: maxHeight,
  34064. updatable: updatable,
  34065. onReady: onReady
  34066. };
  34067. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34068. };
  34069. /**
  34070. * Creates a tube mesh.
  34071. * 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.
  34072. * Please consider using the same method from the MeshBuilder class instead.
  34073. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34074. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34075. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34076. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34077. * 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.
  34078. * It must return a radius value (positive float) :
  34079. * ```javascript
  34080. * var radiusFunction = function(i, distance) {
  34081. * // do things
  34082. * return radius; }
  34083. * ```
  34084. * 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
  34085. * 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
  34086. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34087. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34089. */
  34090. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34091. var options = {
  34092. path: path,
  34093. radius: radius,
  34094. tessellation: tessellation,
  34095. radiusFunction: radiusFunction,
  34096. arc: 1,
  34097. cap: cap,
  34098. updatable: updatable,
  34099. sideOrientation: sideOrientation,
  34100. instance: instance
  34101. };
  34102. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34103. };
  34104. /**
  34105. * Creates a polyhedron mesh.
  34106. * Please consider using the same method from the MeshBuilder class instead.
  34107. * 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
  34108. * to choose the wanted type.
  34109. * The parameter `size` (positive float, default 1) sets the polygon size.
  34110. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34111. * 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`.
  34112. * 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
  34113. * 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)`).
  34114. * 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
  34115. * 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.
  34116. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34117. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34118. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34119. */
  34120. Mesh.CreatePolyhedron = function (name, options, scene) {
  34121. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34122. };
  34123. /**
  34124. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34125. * Please consider using the same method from the MeshBuilder class instead.
  34126. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34127. * 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`).
  34128. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34129. * 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.
  34130. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34131. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34133. */
  34134. Mesh.CreateIcoSphere = function (name, options, scene) {
  34135. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34136. };
  34137. /**
  34138. * Creates a decal mesh.
  34139. * Please consider using the same method from the MeshBuilder class instead.
  34140. * 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.
  34141. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34142. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34143. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34144. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34145. */
  34146. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34147. var options = {
  34148. position: position,
  34149. normal: normal,
  34150. size: size,
  34151. angle: angle
  34152. };
  34153. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34154. };
  34155. // Skeletons
  34156. /**
  34157. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34158. */
  34159. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34160. if (!this._sourcePositions) {
  34161. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34162. if (!source) {
  34163. return this._sourcePositions;
  34164. }
  34165. this._sourcePositions = new Float32Array(source);
  34166. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34167. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34168. }
  34169. }
  34170. return this._sourcePositions;
  34171. };
  34172. /**
  34173. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34174. */
  34175. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34176. if (!this._sourceNormals) {
  34177. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34178. if (!source) {
  34179. return this._sourceNormals;
  34180. }
  34181. this._sourceNormals = new Float32Array(source);
  34182. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34183. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34184. }
  34185. }
  34186. return this._sourceNormals;
  34187. };
  34188. /**
  34189. * Updates the vertex buffer by applying transformation from the bones.
  34190. * Returns the Mesh.
  34191. *
  34192. * @param {skeleton} skeleton to apply
  34193. */
  34194. Mesh.prototype.applySkeleton = function (skeleton) {
  34195. if (!this.geometry) {
  34196. return this;
  34197. }
  34198. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34199. return this;
  34200. }
  34201. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34202. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34203. return this;
  34204. }
  34205. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34206. return this;
  34207. }
  34208. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34209. return this;
  34210. }
  34211. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34212. return this;
  34213. }
  34214. if (!this._sourcePositions) {
  34215. var submeshes = this.subMeshes.slice();
  34216. this.setPositionsForCPUSkinning();
  34217. this.subMeshes = submeshes;
  34218. }
  34219. if (!this._sourceNormals) {
  34220. this.setNormalsForCPUSkinning();
  34221. }
  34222. // positionsData checks for not being Float32Array will only pass at most once
  34223. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34224. if (!positionsData) {
  34225. return this;
  34226. }
  34227. if (!(positionsData instanceof Float32Array)) {
  34228. positionsData = new Float32Array(positionsData);
  34229. }
  34230. // normalsData checks for not being Float32Array will only pass at most once
  34231. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34232. if (!normalsData) {
  34233. return this;
  34234. }
  34235. if (!(normalsData instanceof Float32Array)) {
  34236. normalsData = new Float32Array(normalsData);
  34237. }
  34238. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34239. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34240. if (!matricesWeightsData || !matricesIndicesData) {
  34241. return this;
  34242. }
  34243. var needExtras = this.numBoneInfluencers > 4;
  34244. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34245. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34246. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34247. var tempVector3 = BABYLON.Vector3.Zero();
  34248. var finalMatrix = new BABYLON.Matrix();
  34249. var tempMatrix = new BABYLON.Matrix();
  34250. var matWeightIdx = 0;
  34251. var inf;
  34252. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34253. var weight;
  34254. for (inf = 0; inf < 4; inf++) {
  34255. weight = matricesWeightsData[matWeightIdx + inf];
  34256. if (weight > 0) {
  34257. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34258. finalMatrix.addToSelf(tempMatrix);
  34259. }
  34260. else
  34261. break;
  34262. }
  34263. if (needExtras) {
  34264. for (inf = 0; inf < 4; inf++) {
  34265. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34266. if (weight > 0) {
  34267. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34268. finalMatrix.addToSelf(tempMatrix);
  34269. }
  34270. else
  34271. break;
  34272. }
  34273. }
  34274. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34275. tempVector3.toArray(positionsData, index);
  34276. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34277. tempVector3.toArray(normalsData, index);
  34278. finalMatrix.reset();
  34279. }
  34280. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34281. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34282. return this;
  34283. };
  34284. // Tools
  34285. /**
  34286. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34287. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34288. */
  34289. Mesh.MinMax = function (meshes) {
  34290. var minVector = null;
  34291. var maxVector = null;
  34292. meshes.forEach(function (mesh, index, array) {
  34293. var boundingInfo = mesh.getBoundingInfo();
  34294. var boundingBox = boundingInfo.boundingBox;
  34295. if (!minVector || !maxVector) {
  34296. minVector = boundingBox.minimumWorld;
  34297. maxVector = boundingBox.maximumWorld;
  34298. }
  34299. else {
  34300. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34301. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34302. }
  34303. });
  34304. if (!minVector || !maxVector) {
  34305. return {
  34306. min: BABYLON.Vector3.Zero(),
  34307. max: BABYLON.Vector3.Zero()
  34308. };
  34309. }
  34310. return {
  34311. min: minVector,
  34312. max: maxVector
  34313. };
  34314. };
  34315. /**
  34316. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34317. */
  34318. Mesh.Center = function (meshesOrMinMaxVector) {
  34319. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34320. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34321. };
  34322. /**
  34323. * Merge the array of meshes into a single mesh for performance reasons.
  34324. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34325. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34326. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34327. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34328. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34329. */
  34330. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34331. if (disposeSource === void 0) { disposeSource = true; }
  34332. var index;
  34333. if (!allow32BitsIndices) {
  34334. var totalVertices = 0;
  34335. // Counting vertices
  34336. for (index = 0; index < meshes.length; index++) {
  34337. if (meshes[index]) {
  34338. totalVertices += meshes[index].getTotalVertices();
  34339. if (totalVertices > 65536) {
  34340. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34341. return null;
  34342. }
  34343. }
  34344. }
  34345. }
  34346. // Merge
  34347. var vertexData = null;
  34348. var otherVertexData;
  34349. var indiceArray = new Array();
  34350. var source = null;
  34351. for (index = 0; index < meshes.length; index++) {
  34352. if (meshes[index]) {
  34353. meshes[index].computeWorldMatrix(true);
  34354. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34355. otherVertexData.transform(meshes[index].getWorldMatrix());
  34356. if (vertexData) {
  34357. vertexData.merge(otherVertexData);
  34358. }
  34359. else {
  34360. vertexData = otherVertexData;
  34361. source = meshes[index];
  34362. }
  34363. if (subdivideWithSubMeshes) {
  34364. indiceArray.push(meshes[index].getTotalIndices());
  34365. }
  34366. }
  34367. }
  34368. source = source;
  34369. if (!meshSubclass) {
  34370. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34371. }
  34372. vertexData.applyToMesh(meshSubclass);
  34373. // Setting properties
  34374. meshSubclass.material = source.material;
  34375. meshSubclass.checkCollisions = source.checkCollisions;
  34376. // Cleaning
  34377. if (disposeSource) {
  34378. for (index = 0; index < meshes.length; index++) {
  34379. if (meshes[index]) {
  34380. meshes[index].dispose();
  34381. }
  34382. }
  34383. }
  34384. // Subdivide
  34385. if (subdivideWithSubMeshes) {
  34386. //-- removal of global submesh
  34387. meshSubclass.releaseSubMeshes();
  34388. index = 0;
  34389. var offset = 0;
  34390. //-- apply subdivision according to index table
  34391. while (index < indiceArray.length) {
  34392. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34393. offset += indiceArray[index];
  34394. index++;
  34395. }
  34396. }
  34397. return meshSubclass;
  34398. };
  34399. // Consts
  34400. Mesh._FRONTSIDE = 0;
  34401. Mesh._BACKSIDE = 1;
  34402. Mesh._DOUBLESIDE = 2;
  34403. Mesh._DEFAULTSIDE = 0;
  34404. Mesh._NO_CAP = 0;
  34405. Mesh._CAP_START = 1;
  34406. Mesh._CAP_END = 2;
  34407. Mesh._CAP_ALL = 3;
  34408. return Mesh;
  34409. }(BABYLON.AbstractMesh));
  34410. BABYLON.Mesh = Mesh;
  34411. })(BABYLON || (BABYLON = {}));
  34412. //# sourceMappingURL=babylon.mesh.js.map
  34413. var BABYLON;
  34414. (function (BABYLON) {
  34415. var BaseSubMesh = /** @class */ (function () {
  34416. function BaseSubMesh() {
  34417. }
  34418. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34419. get: function () {
  34420. return this._materialEffect;
  34421. },
  34422. enumerable: true,
  34423. configurable: true
  34424. });
  34425. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34426. if (defines === void 0) { defines = null; }
  34427. if (this._materialEffect === effect) {
  34428. if (!effect) {
  34429. this._materialDefines = null;
  34430. }
  34431. return;
  34432. }
  34433. this._materialDefines = defines;
  34434. this._materialEffect = effect;
  34435. };
  34436. return BaseSubMesh;
  34437. }());
  34438. BABYLON.BaseSubMesh = BaseSubMesh;
  34439. var SubMesh = /** @class */ (function (_super) {
  34440. __extends(SubMesh, _super);
  34441. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34442. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34443. var _this = _super.call(this) || this;
  34444. _this.materialIndex = materialIndex;
  34445. _this.verticesStart = verticesStart;
  34446. _this.verticesCount = verticesCount;
  34447. _this.indexStart = indexStart;
  34448. _this.indexCount = indexCount;
  34449. _this._renderId = 0;
  34450. _this._mesh = mesh;
  34451. _this._renderingMesh = renderingMesh || mesh;
  34452. mesh.subMeshes.push(_this);
  34453. _this._trianglePlanes = [];
  34454. _this._id = mesh.subMeshes.length - 1;
  34455. if (createBoundingBox) {
  34456. _this.refreshBoundingInfo();
  34457. mesh.computeWorldMatrix(true);
  34458. }
  34459. return _this;
  34460. }
  34461. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34462. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34463. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34464. };
  34465. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34466. get: function () {
  34467. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34468. },
  34469. enumerable: true,
  34470. configurable: true
  34471. });
  34472. /**
  34473. * Returns the submesh BoudingInfo object.
  34474. */
  34475. SubMesh.prototype.getBoundingInfo = function () {
  34476. if (this.IsGlobal) {
  34477. return this._mesh.getBoundingInfo();
  34478. }
  34479. return this._boundingInfo;
  34480. };
  34481. /**
  34482. * Sets the submesh BoundingInfo.
  34483. * Return the SubMesh.
  34484. */
  34485. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34486. this._boundingInfo = boundingInfo;
  34487. return this;
  34488. };
  34489. /**
  34490. * Returns the mesh of the current submesh.
  34491. */
  34492. SubMesh.prototype.getMesh = function () {
  34493. return this._mesh;
  34494. };
  34495. /**
  34496. * Returns the rendering mesh of the submesh.
  34497. */
  34498. SubMesh.prototype.getRenderingMesh = function () {
  34499. return this._renderingMesh;
  34500. };
  34501. /**
  34502. * Returns the submesh material.
  34503. */
  34504. SubMesh.prototype.getMaterial = function () {
  34505. var rootMaterial = this._renderingMesh.material;
  34506. if (rootMaterial === null || rootMaterial === undefined) {
  34507. return this._mesh.getScene().defaultMaterial;
  34508. }
  34509. else if (rootMaterial.getSubMaterial) {
  34510. var multiMaterial = rootMaterial;
  34511. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34512. if (this._currentMaterial !== effectiveMaterial) {
  34513. this._currentMaterial = effectiveMaterial;
  34514. this._materialDefines = null;
  34515. }
  34516. return effectiveMaterial;
  34517. }
  34518. return rootMaterial;
  34519. };
  34520. // Methods
  34521. /**
  34522. * Sets a new updated BoundingInfo object to the submesh.
  34523. * Returns the SubMesh.
  34524. */
  34525. SubMesh.prototype.refreshBoundingInfo = function () {
  34526. this._lastColliderWorldVertices = null;
  34527. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34528. return this;
  34529. }
  34530. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34531. if (!data) {
  34532. this._boundingInfo = this._mesh.getBoundingInfo();
  34533. return this;
  34534. }
  34535. var indices = this._renderingMesh.getIndices();
  34536. var extend;
  34537. //is this the only submesh?
  34538. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34539. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34540. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34541. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34542. }
  34543. else {
  34544. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34545. }
  34546. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34547. return this;
  34548. };
  34549. SubMesh.prototype._checkCollision = function (collider) {
  34550. var boundingInfo = this.getBoundingInfo();
  34551. return boundingInfo._checkCollision(collider);
  34552. };
  34553. /**
  34554. * Updates the submesh BoundingInfo.
  34555. * Returns the Submesh.
  34556. */
  34557. SubMesh.prototype.updateBoundingInfo = function (world) {
  34558. var boundingInfo = this.getBoundingInfo();
  34559. if (!boundingInfo) {
  34560. this.refreshBoundingInfo();
  34561. boundingInfo = this.getBoundingInfo();
  34562. }
  34563. boundingInfo.update(world);
  34564. return this;
  34565. };
  34566. /**
  34567. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34568. * Boolean returned.
  34569. */
  34570. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34571. var boundingInfo = this.getBoundingInfo();
  34572. if (!boundingInfo) {
  34573. return false;
  34574. }
  34575. return boundingInfo.isInFrustum(frustumPlanes);
  34576. };
  34577. /**
  34578. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34579. * Boolean returned.
  34580. */
  34581. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34582. var boundingInfo = this.getBoundingInfo();
  34583. if (!boundingInfo) {
  34584. return false;
  34585. }
  34586. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34587. };
  34588. /**
  34589. * Renders the submesh.
  34590. * Returns it.
  34591. */
  34592. SubMesh.prototype.render = function (enableAlphaMode) {
  34593. this._renderingMesh.render(this, enableAlphaMode);
  34594. return this;
  34595. };
  34596. /**
  34597. * Returns a new Index Buffer.
  34598. * Type returned : WebGLBuffer.
  34599. */
  34600. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34601. if (!this._linesIndexBuffer) {
  34602. var linesIndices = [];
  34603. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34604. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34605. }
  34606. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34607. this.linesIndexCount = linesIndices.length;
  34608. }
  34609. return this._linesIndexBuffer;
  34610. };
  34611. /**
  34612. * True is the passed Ray intersects the submesh bounding box.
  34613. * Boolean returned.
  34614. */
  34615. SubMesh.prototype.canIntersects = function (ray) {
  34616. var boundingInfo = this.getBoundingInfo();
  34617. if (!boundingInfo) {
  34618. return false;
  34619. }
  34620. return ray.intersectsBox(boundingInfo.boundingBox);
  34621. };
  34622. /**
  34623. * Returns an object IntersectionInfo.
  34624. */
  34625. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34626. var intersectInfo = null;
  34627. var material = this.getMaterial();
  34628. if (!material) {
  34629. return null;
  34630. }
  34631. switch (material.fillMode) {
  34632. case BABYLON.Material.PointListDrawMode:
  34633. case BABYLON.Material.LineListDrawMode:
  34634. case BABYLON.Material.LineLoopDrawMode:
  34635. case BABYLON.Material.LineStripDrawMode:
  34636. case BABYLON.Material.TriangleFanDrawMode:
  34637. case BABYLON.Material.TriangleStripDrawMode:
  34638. return null;
  34639. }
  34640. // LineMesh first as it's also a Mesh...
  34641. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34642. var lineMesh = this._mesh;
  34643. // Line test
  34644. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34645. var p0 = positions[indices[index]];
  34646. var p1 = positions[indices[index + 1]];
  34647. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34648. if (length < 0) {
  34649. continue;
  34650. }
  34651. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34652. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34653. if (fastCheck) {
  34654. break;
  34655. }
  34656. }
  34657. }
  34658. }
  34659. else {
  34660. // Triangles test
  34661. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34662. var p0 = positions[indices[index]];
  34663. var p1 = positions[indices[index + 1]];
  34664. var p2 = positions[indices[index + 2]];
  34665. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34666. if (currentIntersectInfo) {
  34667. if (currentIntersectInfo.distance < 0) {
  34668. continue;
  34669. }
  34670. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34671. intersectInfo = currentIntersectInfo;
  34672. intersectInfo.faceId = index / 3;
  34673. if (fastCheck) {
  34674. break;
  34675. }
  34676. }
  34677. }
  34678. }
  34679. }
  34680. return intersectInfo;
  34681. };
  34682. SubMesh.prototype._rebuild = function () {
  34683. if (this._linesIndexBuffer) {
  34684. this._linesIndexBuffer = null;
  34685. }
  34686. };
  34687. // Clone
  34688. /**
  34689. * Creates a new Submesh from the passed Mesh.
  34690. */
  34691. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34692. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34693. if (!this.IsGlobal) {
  34694. var boundingInfo = this.getBoundingInfo();
  34695. if (!boundingInfo) {
  34696. return result;
  34697. }
  34698. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34699. }
  34700. return result;
  34701. };
  34702. // Dispose
  34703. /**
  34704. * Disposes the Submesh.
  34705. * Returns nothing.
  34706. */
  34707. SubMesh.prototype.dispose = function () {
  34708. if (this._linesIndexBuffer) {
  34709. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34710. this._linesIndexBuffer = null;
  34711. }
  34712. // Remove from mesh
  34713. var index = this._mesh.subMeshes.indexOf(this);
  34714. this._mesh.subMeshes.splice(index, 1);
  34715. };
  34716. // Statics
  34717. /**
  34718. * Creates a new Submesh from the passed parameters :
  34719. * - materialIndex (integer) : the index of the main mesh material.
  34720. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34721. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34722. * - mesh (Mesh) : the main mesh to create the submesh from.
  34723. * - renderingMesh (optional Mesh) : rendering mesh.
  34724. */
  34725. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34726. var minVertexIndex = Number.MAX_VALUE;
  34727. var maxVertexIndex = -Number.MAX_VALUE;
  34728. renderingMesh = (renderingMesh || mesh);
  34729. var indices = renderingMesh.getIndices();
  34730. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34731. var vertexIndex = indices[index];
  34732. if (vertexIndex < minVertexIndex)
  34733. minVertexIndex = vertexIndex;
  34734. if (vertexIndex > maxVertexIndex)
  34735. maxVertexIndex = vertexIndex;
  34736. }
  34737. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34738. };
  34739. return SubMesh;
  34740. }(BaseSubMesh));
  34741. BABYLON.SubMesh = SubMesh;
  34742. })(BABYLON || (BABYLON = {}));
  34743. //# sourceMappingURL=babylon.subMesh.js.map
  34744. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34745. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34746. s = arguments[i];
  34747. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34748. t[p] = s[p];
  34749. }
  34750. return t;
  34751. };
  34752. var BABYLON;
  34753. (function (BABYLON) {
  34754. /**
  34755. * Manages the defines for the Material
  34756. */
  34757. var MaterialDefines = /** @class */ (function () {
  34758. function MaterialDefines() {
  34759. this._isDirty = true;
  34760. /** @hidden */
  34761. this._areLightsDirty = true;
  34762. /** @hidden */
  34763. this._areAttributesDirty = true;
  34764. /** @hidden */
  34765. this._areTexturesDirty = true;
  34766. /** @hidden */
  34767. this._areFresnelDirty = true;
  34768. /** @hidden */
  34769. this._areMiscDirty = true;
  34770. /** @hidden */
  34771. this._areImageProcessingDirty = true;
  34772. /** @hidden */
  34773. this._normals = false;
  34774. /** @hidden */
  34775. this._uvs = false;
  34776. /** @hidden */
  34777. this._needNormals = false;
  34778. /** @hidden */
  34779. this._needUVs = false;
  34780. }
  34781. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34782. /**
  34783. * Specifies if the material needs to be re-calculated
  34784. */
  34785. get: function () {
  34786. return this._isDirty;
  34787. },
  34788. enumerable: true,
  34789. configurable: true
  34790. });
  34791. /**
  34792. * Marks the material to indicate that it has been re-calculated
  34793. */
  34794. MaterialDefines.prototype.markAsProcessed = function () {
  34795. this._isDirty = false;
  34796. this._areAttributesDirty = false;
  34797. this._areTexturesDirty = false;
  34798. this._areFresnelDirty = false;
  34799. this._areLightsDirty = false;
  34800. this._areMiscDirty = false;
  34801. this._areImageProcessingDirty = false;
  34802. };
  34803. /**
  34804. * Marks the material to indicate that it needs to be re-calculated
  34805. */
  34806. MaterialDefines.prototype.markAsUnprocessed = function () {
  34807. this._isDirty = true;
  34808. };
  34809. /**
  34810. * Marks the material to indicate all of its defines need to be re-calculated
  34811. */
  34812. MaterialDefines.prototype.markAllAsDirty = function () {
  34813. this._areTexturesDirty = true;
  34814. this._areAttributesDirty = true;
  34815. this._areLightsDirty = true;
  34816. this._areFresnelDirty = true;
  34817. this._areMiscDirty = true;
  34818. this._areImageProcessingDirty = true;
  34819. this._isDirty = true;
  34820. };
  34821. /**
  34822. * Marks the material to indicate that image processing needs to be re-calculated
  34823. */
  34824. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34825. this._areImageProcessingDirty = true;
  34826. this._isDirty = true;
  34827. };
  34828. /**
  34829. * Marks the material to indicate the lights need to be re-calculated
  34830. */
  34831. MaterialDefines.prototype.markAsLightDirty = function () {
  34832. this._areLightsDirty = true;
  34833. this._isDirty = true;
  34834. };
  34835. /**
  34836. * Marks the attribute state as changed
  34837. */
  34838. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34839. this._areAttributesDirty = true;
  34840. this._isDirty = true;
  34841. };
  34842. /**
  34843. * Marks the texture state as changed
  34844. */
  34845. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34846. this._areTexturesDirty = true;
  34847. this._isDirty = true;
  34848. };
  34849. /**
  34850. * Marks the fresnel state as changed
  34851. */
  34852. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34853. this._areFresnelDirty = true;
  34854. this._isDirty = true;
  34855. };
  34856. /**
  34857. * Marks the misc state as changed
  34858. */
  34859. MaterialDefines.prototype.markAsMiscDirty = function () {
  34860. this._areMiscDirty = true;
  34861. this._isDirty = true;
  34862. };
  34863. /**
  34864. * Rebuilds the material defines
  34865. */
  34866. MaterialDefines.prototype.rebuild = function () {
  34867. if (this._keys) {
  34868. delete this._keys;
  34869. }
  34870. this._keys = [];
  34871. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34872. var key = _a[_i];
  34873. if (key[0] === "_") {
  34874. continue;
  34875. }
  34876. this._keys.push(key);
  34877. }
  34878. };
  34879. /**
  34880. * Specifies if two material defines are equal
  34881. * @param other - A material define instance to compare to
  34882. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34883. */
  34884. MaterialDefines.prototype.isEqual = function (other) {
  34885. if (this._keys.length !== other._keys.length) {
  34886. return false;
  34887. }
  34888. for (var index = 0; index < this._keys.length; index++) {
  34889. var prop = this._keys[index];
  34890. if (this[prop] !== other[prop]) {
  34891. return false;
  34892. }
  34893. }
  34894. return true;
  34895. };
  34896. /**
  34897. * Clones this instance's defines to another instance
  34898. * @param other - material defines to clone values to
  34899. */
  34900. MaterialDefines.prototype.cloneTo = function (other) {
  34901. if (this._keys.length !== other._keys.length) {
  34902. other._keys = this._keys.slice(0);
  34903. }
  34904. for (var index = 0; index < this._keys.length; index++) {
  34905. var prop = this._keys[index];
  34906. other[prop] = this[prop];
  34907. }
  34908. };
  34909. /**
  34910. * Resets the material define values
  34911. */
  34912. MaterialDefines.prototype.reset = function () {
  34913. for (var index = 0; index < this._keys.length; index++) {
  34914. var prop = this._keys[index];
  34915. var type = typeof this[prop];
  34916. switch (type) {
  34917. case "number":
  34918. this[prop] = 0;
  34919. break;
  34920. case "string":
  34921. this[prop] = "";
  34922. break;
  34923. default:
  34924. this[prop] = false;
  34925. break;
  34926. }
  34927. }
  34928. };
  34929. /**
  34930. * Converts the material define values to a string
  34931. * @returns - String of material define information
  34932. */
  34933. MaterialDefines.prototype.toString = function () {
  34934. var result = "";
  34935. for (var index = 0; index < this._keys.length; index++) {
  34936. var prop = this._keys[index];
  34937. var value = this[prop];
  34938. var type = typeof value;
  34939. switch (type) {
  34940. case "number":
  34941. case "string":
  34942. result += "#define " + prop + " " + value + "\n";
  34943. break;
  34944. default:
  34945. if (value) {
  34946. result += "#define " + prop + "\n";
  34947. }
  34948. break;
  34949. }
  34950. }
  34951. return result;
  34952. };
  34953. return MaterialDefines;
  34954. }());
  34955. BABYLON.MaterialDefines = MaterialDefines;
  34956. /**
  34957. * Base class for the main features of a material in Babylon.js
  34958. */
  34959. var Material = /** @class */ (function () {
  34960. /**
  34961. * Creates a material instance
  34962. * @param name defines the name of the material
  34963. * @param scene defines the scene to reference
  34964. * @param doNotAdd specifies if the material should be added to the scene
  34965. */
  34966. function Material(name, scene, doNotAdd) {
  34967. /**
  34968. * Specifies if the ready state should be checked on each call
  34969. */
  34970. this.checkReadyOnEveryCall = false;
  34971. /**
  34972. * Specifies if the ready state should be checked once
  34973. */
  34974. this.checkReadyOnlyOnce = false;
  34975. /**
  34976. * The state of the material
  34977. */
  34978. this.state = "";
  34979. /**
  34980. * The alpha value of the material
  34981. */
  34982. this._alpha = 1.0;
  34983. /**
  34984. * Specifies if back face culling is enabled
  34985. */
  34986. this._backFaceCulling = true;
  34987. /**
  34988. * Specifies if the material should be serialized
  34989. */
  34990. this.doNotSerialize = false;
  34991. /**
  34992. * Specifies if the effect should be stored on sub meshes
  34993. */
  34994. this.storeEffectOnSubMeshes = false;
  34995. /**
  34996. * An event triggered when the material is disposed
  34997. */
  34998. this.onDisposeObservable = new BABYLON.Observable();
  34999. /**
  35000. * An event triggered when the material is bound
  35001. */
  35002. this.onBindObservable = new BABYLON.Observable();
  35003. /**
  35004. * An event triggered when the material is unbound
  35005. */
  35006. this.onUnBindObservable = new BABYLON.Observable();
  35007. /**
  35008. * Stores the value of the alpha mode
  35009. */
  35010. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35011. /**
  35012. * Stores the state of the need depth pre-pass value
  35013. */
  35014. this._needDepthPrePass = false;
  35015. /**
  35016. * Specifies if depth writing should be disabled
  35017. */
  35018. this.disableDepthWrite = false;
  35019. /**
  35020. * Specifies if depth writing should be forced
  35021. */
  35022. this.forceDepthWrite = false;
  35023. /**
  35024. * Specifies if there should be a separate pass for culling
  35025. */
  35026. this.separateCullingPass = false;
  35027. /**
  35028. * Stores the state specifing if fog should be enabled
  35029. */
  35030. this._fogEnabled = true;
  35031. /**
  35032. * Stores the size of points
  35033. */
  35034. this.pointSize = 1.0;
  35035. /**
  35036. * Stores the z offset value
  35037. */
  35038. this.zOffset = 0;
  35039. /**
  35040. * Specifies if the material was previously ready
  35041. */
  35042. this._wasPreviouslyReady = false;
  35043. /**
  35044. * Stores the fill mode state
  35045. */
  35046. this._fillMode = Material.TriangleFillMode;
  35047. this.name = name;
  35048. this.id = name || BABYLON.Tools.RandomId();
  35049. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35050. this.uniqueId = this._scene.getUniqueId();
  35051. if (this._scene.useRightHandedSystem) {
  35052. this.sideOrientation = Material.ClockWiseSideOrientation;
  35053. }
  35054. else {
  35055. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35056. }
  35057. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35058. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35059. if (!doNotAdd) {
  35060. this._scene.materials.push(this);
  35061. }
  35062. }
  35063. Object.defineProperty(Material, "TriangleFillMode", {
  35064. /**
  35065. * Returns the triangle fill mode
  35066. */
  35067. get: function () {
  35068. return Material._TriangleFillMode;
  35069. },
  35070. enumerable: true,
  35071. configurable: true
  35072. });
  35073. Object.defineProperty(Material, "WireFrameFillMode", {
  35074. /**
  35075. * Returns the wireframe mode
  35076. */
  35077. get: function () {
  35078. return Material._WireFrameFillMode;
  35079. },
  35080. enumerable: true,
  35081. configurable: true
  35082. });
  35083. Object.defineProperty(Material, "PointFillMode", {
  35084. /**
  35085. * Returns the point fill mode
  35086. */
  35087. get: function () {
  35088. return Material._PointFillMode;
  35089. },
  35090. enumerable: true,
  35091. configurable: true
  35092. });
  35093. Object.defineProperty(Material, "PointListDrawMode", {
  35094. /**
  35095. * Returns the point list draw mode
  35096. */
  35097. get: function () {
  35098. return Material._PointListDrawMode;
  35099. },
  35100. enumerable: true,
  35101. configurable: true
  35102. });
  35103. Object.defineProperty(Material, "LineListDrawMode", {
  35104. /**
  35105. * Returns the line list draw mode
  35106. */
  35107. get: function () {
  35108. return Material._LineListDrawMode;
  35109. },
  35110. enumerable: true,
  35111. configurable: true
  35112. });
  35113. Object.defineProperty(Material, "LineLoopDrawMode", {
  35114. /**
  35115. * Returns the line loop draw mode
  35116. */
  35117. get: function () {
  35118. return Material._LineLoopDrawMode;
  35119. },
  35120. enumerable: true,
  35121. configurable: true
  35122. });
  35123. Object.defineProperty(Material, "LineStripDrawMode", {
  35124. /**
  35125. * Returns the line strip draw mode
  35126. */
  35127. get: function () {
  35128. return Material._LineStripDrawMode;
  35129. },
  35130. enumerable: true,
  35131. configurable: true
  35132. });
  35133. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35134. /**
  35135. * Returns the triangle strip draw mode
  35136. */
  35137. get: function () {
  35138. return Material._TriangleStripDrawMode;
  35139. },
  35140. enumerable: true,
  35141. configurable: true
  35142. });
  35143. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35144. /**
  35145. * Returns the triangle fan draw mode
  35146. */
  35147. get: function () {
  35148. return Material._TriangleFanDrawMode;
  35149. },
  35150. enumerable: true,
  35151. configurable: true
  35152. });
  35153. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35154. /**
  35155. * Returns the clock-wise side orientation
  35156. */
  35157. get: function () {
  35158. return Material._ClockWiseSideOrientation;
  35159. },
  35160. enumerable: true,
  35161. configurable: true
  35162. });
  35163. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35164. /**
  35165. * Returns the counter clock-wise side orientation
  35166. */
  35167. get: function () {
  35168. return Material._CounterClockWiseSideOrientation;
  35169. },
  35170. enumerable: true,
  35171. configurable: true
  35172. });
  35173. Object.defineProperty(Material, "TextureDirtyFlag", {
  35174. /**
  35175. * Returns the dirty texture flag value
  35176. */
  35177. get: function () {
  35178. return Material._TextureDirtyFlag;
  35179. },
  35180. enumerable: true,
  35181. configurable: true
  35182. });
  35183. Object.defineProperty(Material, "LightDirtyFlag", {
  35184. /**
  35185. * Returns the dirty light flag value
  35186. */
  35187. get: function () {
  35188. return Material._LightDirtyFlag;
  35189. },
  35190. enumerable: true,
  35191. configurable: true
  35192. });
  35193. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35194. /**
  35195. * Returns the dirty fresnel flag value
  35196. */
  35197. get: function () {
  35198. return Material._FresnelDirtyFlag;
  35199. },
  35200. enumerable: true,
  35201. configurable: true
  35202. });
  35203. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35204. /**
  35205. * Returns the dirty attributes flag value
  35206. */
  35207. get: function () {
  35208. return Material._AttributesDirtyFlag;
  35209. },
  35210. enumerable: true,
  35211. configurable: true
  35212. });
  35213. Object.defineProperty(Material, "MiscDirtyFlag", {
  35214. /**
  35215. * Returns the dirty misc flag value
  35216. */
  35217. get: function () {
  35218. return Material._MiscDirtyFlag;
  35219. },
  35220. enumerable: true,
  35221. configurable: true
  35222. });
  35223. Object.defineProperty(Material.prototype, "alpha", {
  35224. /**
  35225. * Gets the alpha value of the material
  35226. */
  35227. get: function () {
  35228. return this._alpha;
  35229. },
  35230. /**
  35231. * Sets the alpha value of the material
  35232. */
  35233. set: function (value) {
  35234. if (this._alpha === value) {
  35235. return;
  35236. }
  35237. this._alpha = value;
  35238. this.markAsDirty(Material.MiscDirtyFlag);
  35239. },
  35240. enumerable: true,
  35241. configurable: true
  35242. });
  35243. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35244. /**
  35245. * Gets the back-face culling state
  35246. */
  35247. get: function () {
  35248. return this._backFaceCulling;
  35249. },
  35250. /**
  35251. * Sets the back-face culling state
  35252. */
  35253. set: function (value) {
  35254. if (this._backFaceCulling === value) {
  35255. return;
  35256. }
  35257. this._backFaceCulling = value;
  35258. this.markAsDirty(Material.TextureDirtyFlag);
  35259. },
  35260. enumerable: true,
  35261. configurable: true
  35262. });
  35263. Object.defineProperty(Material.prototype, "onDispose", {
  35264. /**
  35265. * Called during a dispose event
  35266. */
  35267. set: function (callback) {
  35268. if (this._onDisposeObserver) {
  35269. this.onDisposeObservable.remove(this._onDisposeObserver);
  35270. }
  35271. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35272. },
  35273. enumerable: true,
  35274. configurable: true
  35275. });
  35276. Object.defineProperty(Material.prototype, "onBind", {
  35277. /**
  35278. * Called during a bind event
  35279. */
  35280. set: function (callback) {
  35281. if (this._onBindObserver) {
  35282. this.onBindObservable.remove(this._onBindObserver);
  35283. }
  35284. this._onBindObserver = this.onBindObservable.add(callback);
  35285. },
  35286. enumerable: true,
  35287. configurable: true
  35288. });
  35289. Object.defineProperty(Material.prototype, "alphaMode", {
  35290. /**
  35291. * Gets the value of the alpha mode
  35292. */
  35293. get: function () {
  35294. return this._alphaMode;
  35295. },
  35296. /**
  35297. * Sets the value of the alpha mode.
  35298. *
  35299. * | Value | Type | Description |
  35300. * | --- | --- | --- |
  35301. * | 0 | ALPHA_DISABLE | |
  35302. * | 1 | ALPHA_ADD | |
  35303. * | 2 | ALPHA_COMBINE | |
  35304. * | 3 | ALPHA_SUBTRACT | |
  35305. * | 4 | ALPHA_MULTIPLY | |
  35306. * | 5 | ALPHA_MAXIMIZED | |
  35307. * | 6 | ALPHA_ONEONE | |
  35308. * | 7 | ALPHA_PREMULTIPLIED | |
  35309. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35310. * | 9 | ALPHA_INTERPOLATE | |
  35311. * | 10 | ALPHA_SCREENMODE | |
  35312. *
  35313. */
  35314. set: function (value) {
  35315. if (this._alphaMode === value) {
  35316. return;
  35317. }
  35318. this._alphaMode = value;
  35319. this.markAsDirty(Material.TextureDirtyFlag);
  35320. },
  35321. enumerable: true,
  35322. configurable: true
  35323. });
  35324. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35325. /**
  35326. * Gets the depth pre-pass value
  35327. */
  35328. get: function () {
  35329. return this._needDepthPrePass;
  35330. },
  35331. /**
  35332. * Sets the need depth pre-pass value
  35333. */
  35334. set: function (value) {
  35335. if (this._needDepthPrePass === value) {
  35336. return;
  35337. }
  35338. this._needDepthPrePass = value;
  35339. if (this._needDepthPrePass) {
  35340. this.checkReadyOnEveryCall = true;
  35341. }
  35342. },
  35343. enumerable: true,
  35344. configurable: true
  35345. });
  35346. Object.defineProperty(Material.prototype, "fogEnabled", {
  35347. /**
  35348. * Gets the value of the fog enabled state
  35349. */
  35350. get: function () {
  35351. return this._fogEnabled;
  35352. },
  35353. /**
  35354. * Sets the state for enabling fog
  35355. */
  35356. set: function (value) {
  35357. if (this._fogEnabled === value) {
  35358. return;
  35359. }
  35360. this._fogEnabled = value;
  35361. this.markAsDirty(Material.MiscDirtyFlag);
  35362. },
  35363. enumerable: true,
  35364. configurable: true
  35365. });
  35366. Object.defineProperty(Material.prototype, "wireframe", {
  35367. /**
  35368. * Gets a value specifying if wireframe mode is enabled
  35369. */
  35370. get: function () {
  35371. switch (this._fillMode) {
  35372. case Material.WireFrameFillMode:
  35373. case Material.LineListDrawMode:
  35374. case Material.LineLoopDrawMode:
  35375. case Material.LineStripDrawMode:
  35376. return true;
  35377. }
  35378. return this._scene.forceWireframe;
  35379. },
  35380. /**
  35381. * Sets the state of wireframe mode
  35382. */
  35383. set: function (value) {
  35384. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35385. },
  35386. enumerable: true,
  35387. configurable: true
  35388. });
  35389. Object.defineProperty(Material.prototype, "pointsCloud", {
  35390. /**
  35391. * Gets the value specifying if point clouds are enabled
  35392. */
  35393. get: function () {
  35394. switch (this._fillMode) {
  35395. case Material.PointFillMode:
  35396. case Material.PointListDrawMode:
  35397. return true;
  35398. }
  35399. return this._scene.forcePointsCloud;
  35400. },
  35401. /**
  35402. * Sets the state of point cloud mode
  35403. */
  35404. set: function (value) {
  35405. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35406. },
  35407. enumerable: true,
  35408. configurable: true
  35409. });
  35410. Object.defineProperty(Material.prototype, "fillMode", {
  35411. /**
  35412. * Gets the material fill mode
  35413. */
  35414. get: function () {
  35415. return this._fillMode;
  35416. },
  35417. /**
  35418. * Sets the material fill mode
  35419. */
  35420. set: function (value) {
  35421. if (this._fillMode === value) {
  35422. return;
  35423. }
  35424. this._fillMode = value;
  35425. this.markAsDirty(Material.MiscDirtyFlag);
  35426. },
  35427. enumerable: true,
  35428. configurable: true
  35429. });
  35430. /**
  35431. * Returns a string representation of the current material
  35432. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35433. * @returns a string with material information
  35434. */
  35435. Material.prototype.toString = function (fullDetails) {
  35436. var ret = "Name: " + this.name;
  35437. if (fullDetails) {
  35438. }
  35439. return ret;
  35440. };
  35441. /**
  35442. * Gets the class name of the material
  35443. * @returns a string with the class name of the material
  35444. */
  35445. Material.prototype.getClassName = function () {
  35446. return "Material";
  35447. };
  35448. Object.defineProperty(Material.prototype, "isFrozen", {
  35449. /**
  35450. * Specifies if updates for the material been locked
  35451. */
  35452. get: function () {
  35453. return this.checkReadyOnlyOnce;
  35454. },
  35455. enumerable: true,
  35456. configurable: true
  35457. });
  35458. /**
  35459. * Locks updates for the material
  35460. */
  35461. Material.prototype.freeze = function () {
  35462. this.checkReadyOnlyOnce = true;
  35463. };
  35464. /**
  35465. * Unlocks updates for the material
  35466. */
  35467. Material.prototype.unfreeze = function () {
  35468. this.checkReadyOnlyOnce = false;
  35469. };
  35470. /**
  35471. * Specifies if the material is ready to be used
  35472. * @param mesh defines the mesh to check
  35473. * @param useInstances specifies if instances should be used
  35474. * @returns a boolean indicating if the material is ready to be used
  35475. */
  35476. Material.prototype.isReady = function (mesh, useInstances) {
  35477. return true;
  35478. };
  35479. /**
  35480. * Specifies that the submesh is ready to be used
  35481. * @param mesh defines the mesh to check
  35482. * @param subMesh defines which submesh to check
  35483. * @param useInstances specifies that instances should be used
  35484. * @returns a boolean indicating that the submesh is ready or not
  35485. */
  35486. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35487. return false;
  35488. };
  35489. /**
  35490. * Returns the material effect
  35491. * @returns the effect associated with the material
  35492. */
  35493. Material.prototype.getEffect = function () {
  35494. return this._effect;
  35495. };
  35496. /**
  35497. * Returns the current scene
  35498. * @returns a Scene
  35499. */
  35500. Material.prototype.getScene = function () {
  35501. return this._scene;
  35502. };
  35503. /**
  35504. * Specifies if the material will require alpha blending
  35505. * @returns a boolean specifying if alpha blending is needed
  35506. */
  35507. Material.prototype.needAlphaBlending = function () {
  35508. return (this.alpha < 1.0);
  35509. };
  35510. /**
  35511. * Specifies if the mesh will require alpha blending
  35512. * @param mesh defines the mesh to check
  35513. * @returns a boolean specifying if alpha blending is needed for the mesh
  35514. */
  35515. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35516. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35517. };
  35518. /**
  35519. * Specifies if this material should be rendered in alpha test mode
  35520. * @returns a boolean specifying if an alpha test is needed.
  35521. */
  35522. Material.prototype.needAlphaTesting = function () {
  35523. return false;
  35524. };
  35525. /**
  35526. * Gets the texture used for the alpha test
  35527. * @returns the texture to use for alpha testing
  35528. */
  35529. Material.prototype.getAlphaTestTexture = function () {
  35530. return null;
  35531. };
  35532. /**
  35533. * Marks the material to indicate that it needs to be re-calculated
  35534. */
  35535. Material.prototype.markDirty = function () {
  35536. this._wasPreviouslyReady = false;
  35537. };
  35538. /** @hidden */
  35539. Material.prototype._preBind = function (effect, overrideOrientation) {
  35540. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35541. var engine = this._scene.getEngine();
  35542. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35543. var reverse = orientation === Material.ClockWiseSideOrientation;
  35544. engine.enableEffect(effect ? effect : this._effect);
  35545. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35546. return reverse;
  35547. };
  35548. /**
  35549. * Binds the material to the mesh
  35550. * @param world defines the world transformation matrix
  35551. * @param mesh defines the mesh to bind the material to
  35552. */
  35553. Material.prototype.bind = function (world, mesh) {
  35554. };
  35555. /**
  35556. * Binds the submesh to the material
  35557. * @param world defines the world transformation matrix
  35558. * @param mesh defines the mesh containing the submesh
  35559. * @param subMesh defines the submesh to bind the material to
  35560. */
  35561. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35562. };
  35563. /**
  35564. * Binds the world matrix to the material
  35565. * @param world defines the world transformation matrix
  35566. */
  35567. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35568. };
  35569. /**
  35570. * Binds the scene's uniform buffer to the effect.
  35571. * @param effect defines the effect to bind to the scene uniform buffer
  35572. * @param sceneUbo defines the uniform buffer storing scene data
  35573. */
  35574. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35575. sceneUbo.bindToEffect(effect, "Scene");
  35576. };
  35577. /**
  35578. * Binds the view matrix to the effect
  35579. * @param effect defines the effect to bind the view matrix to
  35580. */
  35581. Material.prototype.bindView = function (effect) {
  35582. if (!this._useUBO) {
  35583. effect.setMatrix("view", this.getScene().getViewMatrix());
  35584. }
  35585. else {
  35586. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35587. }
  35588. };
  35589. /**
  35590. * Binds the view projection matrix to the effect
  35591. * @param effect defines the effect to bind the view projection matrix to
  35592. */
  35593. Material.prototype.bindViewProjection = function (effect) {
  35594. if (!this._useUBO) {
  35595. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35596. }
  35597. else {
  35598. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35599. }
  35600. };
  35601. /**
  35602. * Specifies if material alpha testing should be turned on for the mesh
  35603. * @param mesh defines the mesh to check
  35604. */
  35605. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35606. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35607. };
  35608. /**
  35609. * Processes to execute after binding the material to a mesh
  35610. * @param mesh defines the rendered mesh
  35611. */
  35612. Material.prototype._afterBind = function (mesh) {
  35613. this._scene._cachedMaterial = this;
  35614. if (mesh) {
  35615. this._scene._cachedVisibility = mesh.visibility;
  35616. }
  35617. else {
  35618. this._scene._cachedVisibility = 1;
  35619. }
  35620. if (mesh) {
  35621. this.onBindObservable.notifyObservers(mesh);
  35622. }
  35623. if (this.disableDepthWrite) {
  35624. var engine = this._scene.getEngine();
  35625. this._cachedDepthWriteState = engine.getDepthWrite();
  35626. engine.setDepthWrite(false);
  35627. }
  35628. };
  35629. /**
  35630. * Unbinds the material from the mesh
  35631. */
  35632. Material.prototype.unbind = function () {
  35633. this.onUnBindObservable.notifyObservers(this);
  35634. if (this.disableDepthWrite) {
  35635. var engine = this._scene.getEngine();
  35636. engine.setDepthWrite(this._cachedDepthWriteState);
  35637. }
  35638. };
  35639. /**
  35640. * Gets the active textures from the material
  35641. * @returns an array of textures
  35642. */
  35643. Material.prototype.getActiveTextures = function () {
  35644. return [];
  35645. };
  35646. /**
  35647. * Specifies if the material uses a texture
  35648. * @param texture defines the texture to check against the material
  35649. * @returns a boolean specifying if the material uses the texture
  35650. */
  35651. Material.prototype.hasTexture = function (texture) {
  35652. return false;
  35653. };
  35654. /**
  35655. * Makes a duplicate of the material, and gives it a new name
  35656. * @param name defines the new name for the duplicated material
  35657. * @returns the cloned material
  35658. */
  35659. Material.prototype.clone = function (name) {
  35660. return null;
  35661. };
  35662. /**
  35663. * Gets the meshes bound to the material
  35664. * @returns an array of meshes bound to the material
  35665. */
  35666. Material.prototype.getBindedMeshes = function () {
  35667. var result = new Array();
  35668. for (var index = 0; index < this._scene.meshes.length; index++) {
  35669. var mesh = this._scene.meshes[index];
  35670. if (mesh.material === this) {
  35671. result.push(mesh);
  35672. }
  35673. }
  35674. return result;
  35675. };
  35676. /**
  35677. * Force shader compilation
  35678. * @param mesh defines the mesh associated with this material
  35679. * @param onCompiled defines a function to execute once the material is compiled
  35680. * @param options defines the options to configure the compilation
  35681. */
  35682. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35683. var _this = this;
  35684. var localOptions = __assign({ clipPlane: false }, options);
  35685. var subMesh = new BABYLON.BaseSubMesh();
  35686. var scene = this.getScene();
  35687. var checkReady = function () {
  35688. if (!_this._scene || !_this._scene.getEngine()) {
  35689. return;
  35690. }
  35691. if (subMesh._materialDefines) {
  35692. subMesh._materialDefines._renderId = -1;
  35693. }
  35694. var clipPlaneState = scene.clipPlane;
  35695. if (localOptions.clipPlane) {
  35696. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35697. }
  35698. if (_this.storeEffectOnSubMeshes) {
  35699. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35700. if (onCompiled) {
  35701. onCompiled(_this);
  35702. }
  35703. }
  35704. else {
  35705. setTimeout(checkReady, 16);
  35706. }
  35707. }
  35708. else {
  35709. if (_this.isReady(mesh)) {
  35710. if (onCompiled) {
  35711. onCompiled(_this);
  35712. }
  35713. }
  35714. else {
  35715. setTimeout(checkReady, 16);
  35716. }
  35717. }
  35718. if (localOptions.clipPlane) {
  35719. scene.clipPlane = clipPlaneState;
  35720. }
  35721. };
  35722. checkReady();
  35723. };
  35724. /**
  35725. * Force shader compilation
  35726. * @param mesh defines the mesh that will use this material
  35727. * @param options defines additional options for compiling the shaders
  35728. * @returns a promise that resolves when the compilation completes
  35729. */
  35730. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35731. var _this = this;
  35732. return new Promise(function (resolve) {
  35733. _this.forceCompilation(mesh, function () {
  35734. resolve();
  35735. }, options);
  35736. });
  35737. };
  35738. /**
  35739. * Marks a define in the material to indicate that it needs to be re-computed
  35740. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35741. */
  35742. Material.prototype.markAsDirty = function (flag) {
  35743. if (flag & Material.TextureDirtyFlag) {
  35744. this._markAllSubMeshesAsTexturesDirty();
  35745. }
  35746. if (flag & Material.LightDirtyFlag) {
  35747. this._markAllSubMeshesAsLightsDirty();
  35748. }
  35749. if (flag & Material.FresnelDirtyFlag) {
  35750. this._markAllSubMeshesAsFresnelDirty();
  35751. }
  35752. if (flag & Material.AttributesDirtyFlag) {
  35753. this._markAllSubMeshesAsAttributesDirty();
  35754. }
  35755. if (flag & Material.MiscDirtyFlag) {
  35756. this._markAllSubMeshesAsMiscDirty();
  35757. }
  35758. this.getScene().resetCachedMaterial();
  35759. };
  35760. /**
  35761. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35762. * @param func defines a function which checks material defines against the submeshes
  35763. */
  35764. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35765. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35766. var mesh = _a[_i];
  35767. if (!mesh.subMeshes) {
  35768. continue;
  35769. }
  35770. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35771. var subMesh = _c[_b];
  35772. if (subMesh.getMaterial() !== this) {
  35773. continue;
  35774. }
  35775. if (!subMesh._materialDefines) {
  35776. continue;
  35777. }
  35778. func(subMesh._materialDefines);
  35779. }
  35780. }
  35781. };
  35782. /**
  35783. * Indicates that image processing needs to be re-calculated for all submeshes
  35784. */
  35785. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35786. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35787. };
  35788. /**
  35789. * Indicates that textures need to be re-calculated for all submeshes
  35790. */
  35791. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35792. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35793. };
  35794. /**
  35795. * Indicates that fresnel needs to be re-calculated for all submeshes
  35796. */
  35797. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35798. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35799. };
  35800. /**
  35801. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35802. */
  35803. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35804. this._markAllSubMeshesAsDirty(function (defines) {
  35805. defines.markAsFresnelDirty();
  35806. defines.markAsMiscDirty();
  35807. });
  35808. };
  35809. /**
  35810. * Indicates that lights need to be re-calculated for all submeshes
  35811. */
  35812. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35813. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35814. };
  35815. /**
  35816. * Indicates that attributes need to be re-calculated for all submeshes
  35817. */
  35818. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35819. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35820. };
  35821. /**
  35822. * Indicates that misc needs to be re-calculated for all submeshes
  35823. */
  35824. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35825. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35826. };
  35827. /**
  35828. * Indicates that textures and misc need to be re-calculated for all submeshes
  35829. */
  35830. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35831. this._markAllSubMeshesAsDirty(function (defines) {
  35832. defines.markAsTexturesDirty();
  35833. defines.markAsMiscDirty();
  35834. });
  35835. };
  35836. /**
  35837. * Disposes the material
  35838. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35839. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35840. */
  35841. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35842. // Animations
  35843. this.getScene().stopAnimation(this);
  35844. this.getScene().freeProcessedMaterials();
  35845. // Remove from scene
  35846. var index = this._scene.materials.indexOf(this);
  35847. if (index >= 0) {
  35848. this._scene.materials.splice(index, 1);
  35849. }
  35850. // Remove from meshes
  35851. for (index = 0; index < this._scene.meshes.length; index++) {
  35852. var mesh = this._scene.meshes[index];
  35853. if (mesh.material === this) {
  35854. mesh.material = null;
  35855. if (mesh.geometry) {
  35856. var geometry = (mesh.geometry);
  35857. if (this.storeEffectOnSubMeshes) {
  35858. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35859. var subMesh = _a[_i];
  35860. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35861. if (forceDisposeEffect && subMesh._materialEffect) {
  35862. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35863. }
  35864. }
  35865. }
  35866. else {
  35867. geometry._releaseVertexArrayObject(this._effect);
  35868. }
  35869. }
  35870. }
  35871. }
  35872. this._uniformBuffer.dispose();
  35873. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35874. if (forceDisposeEffect && this._effect) {
  35875. if (!this.storeEffectOnSubMeshes) {
  35876. this._scene.getEngine()._releaseEffect(this._effect);
  35877. }
  35878. this._effect = null;
  35879. }
  35880. // Callback
  35881. this.onDisposeObservable.notifyObservers(this);
  35882. this.onDisposeObservable.clear();
  35883. this.onBindObservable.clear();
  35884. this.onUnBindObservable.clear();
  35885. };
  35886. /**
  35887. * Serializes this material
  35888. * @returns the serialized material object
  35889. */
  35890. Material.prototype.serialize = function () {
  35891. return BABYLON.SerializationHelper.Serialize(this);
  35892. };
  35893. /**
  35894. * Creates a MultiMaterial from parsed MultiMaterial data.
  35895. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35896. * @param scene defines the hosting scene
  35897. * @returns a new MultiMaterial
  35898. */
  35899. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35900. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35901. multiMaterial.id = parsedMultiMaterial.id;
  35902. if (BABYLON.Tags) {
  35903. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35904. }
  35905. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35906. var subMatId = parsedMultiMaterial.materials[matIndex];
  35907. if (subMatId) {
  35908. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35909. }
  35910. else {
  35911. multiMaterial.subMaterials.push(null);
  35912. }
  35913. }
  35914. return multiMaterial;
  35915. };
  35916. /**
  35917. * Creates a material from parsed material data
  35918. * @param parsedMaterial defines parsed material data
  35919. * @param scene defines the hosting scene
  35920. * @param rootUrl defines the root URL to use to load textures
  35921. * @returns a new material
  35922. */
  35923. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35924. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35925. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35926. }
  35927. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35928. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35929. if (!BABYLON.LegacyPBRMaterial) {
  35930. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35931. return;
  35932. }
  35933. }
  35934. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35935. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35936. };
  35937. // Triangle views
  35938. Material._TriangleFillMode = 0;
  35939. Material._WireFrameFillMode = 1;
  35940. Material._PointFillMode = 2;
  35941. // Draw modes
  35942. Material._PointListDrawMode = 3;
  35943. Material._LineListDrawMode = 4;
  35944. Material._LineLoopDrawMode = 5;
  35945. Material._LineStripDrawMode = 6;
  35946. Material._TriangleStripDrawMode = 7;
  35947. Material._TriangleFanDrawMode = 8;
  35948. /**
  35949. * Stores the clock-wise side orientation
  35950. */
  35951. Material._ClockWiseSideOrientation = 0;
  35952. /**
  35953. * Stores the counter clock-wise side orientation
  35954. */
  35955. Material._CounterClockWiseSideOrientation = 1;
  35956. /**
  35957. * The dirty texture flag value
  35958. */
  35959. Material._TextureDirtyFlag = 1;
  35960. /**
  35961. * The dirty light flag value
  35962. */
  35963. Material._LightDirtyFlag = 2;
  35964. /**
  35965. * The dirty fresnel flag value
  35966. */
  35967. Material._FresnelDirtyFlag = 4;
  35968. /**
  35969. * The dirty attribute flag value
  35970. */
  35971. Material._AttributesDirtyFlag = 8;
  35972. /**
  35973. * The dirty misc flag value
  35974. */
  35975. Material._MiscDirtyFlag = 16;
  35976. __decorate([
  35977. BABYLON.serialize()
  35978. ], Material.prototype, "id", void 0);
  35979. __decorate([
  35980. BABYLON.serialize()
  35981. ], Material.prototype, "uniqueId", void 0);
  35982. __decorate([
  35983. BABYLON.serialize()
  35984. ], Material.prototype, "name", void 0);
  35985. __decorate([
  35986. BABYLON.serialize()
  35987. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35988. __decorate([
  35989. BABYLON.serialize()
  35990. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35991. __decorate([
  35992. BABYLON.serialize()
  35993. ], Material.prototype, "state", void 0);
  35994. __decorate([
  35995. BABYLON.serialize("alpha")
  35996. ], Material.prototype, "_alpha", void 0);
  35997. __decorate([
  35998. BABYLON.serialize("backFaceCulling")
  35999. ], Material.prototype, "_backFaceCulling", void 0);
  36000. __decorate([
  36001. BABYLON.serialize()
  36002. ], Material.prototype, "sideOrientation", void 0);
  36003. __decorate([
  36004. BABYLON.serialize("alphaMode")
  36005. ], Material.prototype, "_alphaMode", void 0);
  36006. __decorate([
  36007. BABYLON.serialize()
  36008. ], Material.prototype, "_needDepthPrePass", void 0);
  36009. __decorate([
  36010. BABYLON.serialize()
  36011. ], Material.prototype, "disableDepthWrite", void 0);
  36012. __decorate([
  36013. BABYLON.serialize()
  36014. ], Material.prototype, "forceDepthWrite", void 0);
  36015. __decorate([
  36016. BABYLON.serialize()
  36017. ], Material.prototype, "separateCullingPass", void 0);
  36018. __decorate([
  36019. BABYLON.serialize("fogEnabled")
  36020. ], Material.prototype, "_fogEnabled", void 0);
  36021. __decorate([
  36022. BABYLON.serialize()
  36023. ], Material.prototype, "pointSize", void 0);
  36024. __decorate([
  36025. BABYLON.serialize()
  36026. ], Material.prototype, "zOffset", void 0);
  36027. __decorate([
  36028. BABYLON.serialize()
  36029. ], Material.prototype, "wireframe", null);
  36030. __decorate([
  36031. BABYLON.serialize()
  36032. ], Material.prototype, "pointsCloud", null);
  36033. __decorate([
  36034. BABYLON.serialize()
  36035. ], Material.prototype, "fillMode", null);
  36036. return Material;
  36037. }());
  36038. BABYLON.Material = Material;
  36039. })(BABYLON || (BABYLON = {}));
  36040. //# sourceMappingURL=babylon.material.js.map
  36041. var BABYLON;
  36042. (function (BABYLON) {
  36043. var UniformBuffer = /** @class */ (function () {
  36044. /**
  36045. * Uniform buffer objects.
  36046. *
  36047. * Handles blocks of uniform on the GPU.
  36048. *
  36049. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36050. *
  36051. * For more information, please refer to :
  36052. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36053. */
  36054. function UniformBuffer(engine, data, dynamic) {
  36055. this._engine = engine;
  36056. this._noUBO = !engine.supportsUniformBuffers;
  36057. this._dynamic = dynamic;
  36058. this._data = data || [];
  36059. this._uniformLocations = {};
  36060. this._uniformSizes = {};
  36061. this._uniformLocationPointer = 0;
  36062. this._needSync = false;
  36063. if (this._noUBO) {
  36064. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36065. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36066. this.updateFloat = this._updateFloatForEffect;
  36067. this.updateFloat2 = this._updateFloat2ForEffect;
  36068. this.updateFloat3 = this._updateFloat3ForEffect;
  36069. this.updateFloat4 = this._updateFloat4ForEffect;
  36070. this.updateMatrix = this._updateMatrixForEffect;
  36071. this.updateVector3 = this._updateVector3ForEffect;
  36072. this.updateVector4 = this._updateVector4ForEffect;
  36073. this.updateColor3 = this._updateColor3ForEffect;
  36074. this.updateColor4 = this._updateColor4ForEffect;
  36075. }
  36076. else {
  36077. this._engine._uniformBuffers.push(this);
  36078. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36079. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36080. this.updateFloat = this._updateFloatForUniform;
  36081. this.updateFloat2 = this._updateFloat2ForUniform;
  36082. this.updateFloat3 = this._updateFloat3ForUniform;
  36083. this.updateFloat4 = this._updateFloat4ForUniform;
  36084. this.updateMatrix = this._updateMatrixForUniform;
  36085. this.updateVector3 = this._updateVector3ForUniform;
  36086. this.updateVector4 = this._updateVector4ForUniform;
  36087. this.updateColor3 = this._updateColor3ForUniform;
  36088. this.updateColor4 = this._updateColor4ForUniform;
  36089. }
  36090. }
  36091. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36092. // Properties
  36093. /**
  36094. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36095. * or just falling back on setUniformXXX calls.
  36096. */
  36097. get: function () {
  36098. return !this._noUBO;
  36099. },
  36100. enumerable: true,
  36101. configurable: true
  36102. });
  36103. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36104. /**
  36105. * Indicates if the WebGL underlying uniform buffer is in sync
  36106. * with the javascript cache data.
  36107. */
  36108. get: function () {
  36109. return !this._needSync;
  36110. },
  36111. enumerable: true,
  36112. configurable: true
  36113. });
  36114. /**
  36115. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36116. * Also, a dynamic UniformBuffer will disable cache verification and always
  36117. * update the underlying WebGL uniform buffer to the GPU.
  36118. */
  36119. UniformBuffer.prototype.isDynamic = function () {
  36120. return this._dynamic !== undefined;
  36121. };
  36122. /**
  36123. * The data cache on JS side.
  36124. */
  36125. UniformBuffer.prototype.getData = function () {
  36126. return this._bufferData;
  36127. };
  36128. /**
  36129. * The underlying WebGL Uniform buffer.
  36130. */
  36131. UniformBuffer.prototype.getBuffer = function () {
  36132. return this._buffer;
  36133. };
  36134. /**
  36135. * std140 layout specifies how to align data within an UBO structure.
  36136. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36137. * for specs.
  36138. */
  36139. UniformBuffer.prototype._fillAlignment = function (size) {
  36140. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36141. // and 4x4 matrices
  36142. // TODO : change if other types are used
  36143. var alignment;
  36144. if (size <= 2) {
  36145. alignment = size;
  36146. }
  36147. else {
  36148. alignment = 4;
  36149. }
  36150. if ((this._uniformLocationPointer % alignment) !== 0) {
  36151. var oldPointer = this._uniformLocationPointer;
  36152. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36153. var diff = this._uniformLocationPointer - oldPointer;
  36154. for (var i = 0; i < diff; i++) {
  36155. this._data.push(0);
  36156. }
  36157. }
  36158. };
  36159. /**
  36160. * Adds an uniform in the buffer.
  36161. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36162. * for the layout to be correct !
  36163. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36164. * @param {number|number[]} size Data size, or data directly.
  36165. */
  36166. UniformBuffer.prototype.addUniform = function (name, size) {
  36167. if (this._noUBO) {
  36168. return;
  36169. }
  36170. if (this._uniformLocations[name] !== undefined) {
  36171. // Already existing uniform
  36172. return;
  36173. }
  36174. // This function must be called in the order of the shader layout !
  36175. // size can be the size of the uniform, or data directly
  36176. var data;
  36177. if (size instanceof Array) {
  36178. data = size;
  36179. size = data.length;
  36180. }
  36181. else {
  36182. size = size;
  36183. data = [];
  36184. // Fill with zeros
  36185. for (var i = 0; i < size; i++) {
  36186. data.push(0);
  36187. }
  36188. }
  36189. this._fillAlignment(size);
  36190. this._uniformSizes[name] = size;
  36191. this._uniformLocations[name] = this._uniformLocationPointer;
  36192. this._uniformLocationPointer += size;
  36193. for (var i = 0; i < size; i++) {
  36194. this._data.push(data[i]);
  36195. }
  36196. this._needSync = true;
  36197. };
  36198. /**
  36199. * Wrapper for addUniform.
  36200. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36201. * @param {Matrix} mat A 4x4 matrix.
  36202. */
  36203. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36204. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36205. };
  36206. /**
  36207. * Wrapper for addUniform.
  36208. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36209. * @param {number} x
  36210. * @param {number} y
  36211. */
  36212. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36213. var temp = [x, y];
  36214. this.addUniform(name, temp);
  36215. };
  36216. /**
  36217. * Wrapper for addUniform.
  36218. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36219. * @param {number} x
  36220. * @param {number} y
  36221. * @param {number} z
  36222. */
  36223. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36224. var temp = [x, y, z];
  36225. this.addUniform(name, temp);
  36226. };
  36227. /**
  36228. * Wrapper for addUniform.
  36229. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36230. * @param {Color3} color
  36231. */
  36232. UniformBuffer.prototype.addColor3 = function (name, color) {
  36233. var temp = new Array();
  36234. color.toArray(temp);
  36235. this.addUniform(name, temp);
  36236. };
  36237. /**
  36238. * Wrapper for addUniform.
  36239. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36240. * @param {Color3} color
  36241. * @param {number} alpha
  36242. */
  36243. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36244. var temp = new Array();
  36245. color.toArray(temp);
  36246. temp.push(alpha);
  36247. this.addUniform(name, temp);
  36248. };
  36249. /**
  36250. * Wrapper for addUniform.
  36251. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36252. * @param {Vector3} vector
  36253. */
  36254. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36255. var temp = new Array();
  36256. vector.toArray(temp);
  36257. this.addUniform(name, temp);
  36258. };
  36259. /**
  36260. * Wrapper for addUniform.
  36261. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36262. */
  36263. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36264. this.addUniform(name, 12);
  36265. };
  36266. /**
  36267. * Wrapper for addUniform.
  36268. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36269. */
  36270. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36271. this.addUniform(name, 8);
  36272. };
  36273. /**
  36274. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36275. */
  36276. UniformBuffer.prototype.create = function () {
  36277. if (this._noUBO) {
  36278. return;
  36279. }
  36280. if (this._buffer) {
  36281. return; // nothing to do
  36282. }
  36283. // See spec, alignment must be filled as a vec4
  36284. this._fillAlignment(4);
  36285. this._bufferData = new Float32Array(this._data);
  36286. this._rebuild();
  36287. this._needSync = true;
  36288. };
  36289. UniformBuffer.prototype._rebuild = function () {
  36290. if (this._noUBO) {
  36291. return;
  36292. }
  36293. if (this._dynamic) {
  36294. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36295. }
  36296. else {
  36297. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36298. }
  36299. };
  36300. /**
  36301. * Updates the WebGL Uniform Buffer on the GPU.
  36302. * If the `dynamic` flag is set to true, no cache comparison is done.
  36303. * Otherwise, the buffer will be updated only if the cache differs.
  36304. */
  36305. UniformBuffer.prototype.update = function () {
  36306. if (!this._buffer) {
  36307. this.create();
  36308. return;
  36309. }
  36310. if (!this._dynamic && !this._needSync) {
  36311. return;
  36312. }
  36313. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36314. this._needSync = false;
  36315. };
  36316. /**
  36317. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36318. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36319. * @param {number[]|Float32Array} data Flattened data
  36320. * @param {number} size Size of the data.
  36321. */
  36322. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36323. var location = this._uniformLocations[uniformName];
  36324. if (location === undefined) {
  36325. if (this._buffer) {
  36326. // Cannot add an uniform if the buffer is already created
  36327. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36328. return;
  36329. }
  36330. this.addUniform(uniformName, size);
  36331. location = this._uniformLocations[uniformName];
  36332. }
  36333. if (!this._buffer) {
  36334. this.create();
  36335. }
  36336. if (!this._dynamic) {
  36337. // Cache for static uniform buffers
  36338. var changed = false;
  36339. for (var i = 0; i < size; i++) {
  36340. if (this._bufferData[location + i] !== data[i]) {
  36341. changed = true;
  36342. this._bufferData[location + i] = data[i];
  36343. }
  36344. }
  36345. this._needSync = this._needSync || changed;
  36346. }
  36347. else {
  36348. // No cache for dynamic
  36349. for (var i = 0; i < size; i++) {
  36350. this._bufferData[location + i] = data[i];
  36351. }
  36352. }
  36353. };
  36354. // Update methods
  36355. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36356. // To match std140, matrix must be realigned
  36357. for (var i = 0; i < 3; i++) {
  36358. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36359. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36360. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36361. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36362. }
  36363. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36364. };
  36365. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36366. this._currentEffect.setMatrix3x3(name, matrix);
  36367. };
  36368. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36369. this._currentEffect.setMatrix2x2(name, matrix);
  36370. };
  36371. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36372. // To match std140, matrix must be realigned
  36373. for (var i = 0; i < 2; i++) {
  36374. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36375. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36376. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36377. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36378. }
  36379. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36380. };
  36381. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36382. this._currentEffect.setFloat(name, x);
  36383. };
  36384. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36385. UniformBuffer._tempBuffer[0] = x;
  36386. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36387. };
  36388. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36389. if (suffix === void 0) { suffix = ""; }
  36390. this._currentEffect.setFloat2(name + suffix, x, y);
  36391. };
  36392. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36393. if (suffix === void 0) { suffix = ""; }
  36394. UniformBuffer._tempBuffer[0] = x;
  36395. UniformBuffer._tempBuffer[1] = y;
  36396. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36397. };
  36398. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36399. if (suffix === void 0) { suffix = ""; }
  36400. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36401. };
  36402. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36403. if (suffix === void 0) { suffix = ""; }
  36404. UniformBuffer._tempBuffer[0] = x;
  36405. UniformBuffer._tempBuffer[1] = y;
  36406. UniformBuffer._tempBuffer[2] = z;
  36407. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36408. };
  36409. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36410. if (suffix === void 0) { suffix = ""; }
  36411. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36412. };
  36413. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36414. if (suffix === void 0) { suffix = ""; }
  36415. UniformBuffer._tempBuffer[0] = x;
  36416. UniformBuffer._tempBuffer[1] = y;
  36417. UniformBuffer._tempBuffer[2] = z;
  36418. UniformBuffer._tempBuffer[3] = w;
  36419. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36420. };
  36421. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36422. this._currentEffect.setMatrix(name, mat);
  36423. };
  36424. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36425. this.updateUniform(name, mat.toArray(), 16);
  36426. };
  36427. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36428. this._currentEffect.setVector3(name, vector);
  36429. };
  36430. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36431. vector.toArray(UniformBuffer._tempBuffer);
  36432. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36433. };
  36434. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36435. this._currentEffect.setVector4(name, vector);
  36436. };
  36437. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36438. vector.toArray(UniformBuffer._tempBuffer);
  36439. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36440. };
  36441. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36442. if (suffix === void 0) { suffix = ""; }
  36443. this._currentEffect.setColor3(name + suffix, color);
  36444. };
  36445. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36446. if (suffix === void 0) { suffix = ""; }
  36447. color.toArray(UniformBuffer._tempBuffer);
  36448. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36449. };
  36450. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36451. if (suffix === void 0) { suffix = ""; }
  36452. this._currentEffect.setColor4(name + suffix, color, alpha);
  36453. };
  36454. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36455. if (suffix === void 0) { suffix = ""; }
  36456. color.toArray(UniformBuffer._tempBuffer);
  36457. UniformBuffer._tempBuffer[3] = alpha;
  36458. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36459. };
  36460. /**
  36461. * Sets a sampler uniform on the effect.
  36462. * @param {string} name Name of the sampler.
  36463. * @param {Texture} texture
  36464. */
  36465. UniformBuffer.prototype.setTexture = function (name, texture) {
  36466. this._currentEffect.setTexture(name, texture);
  36467. };
  36468. /**
  36469. * Directly updates the value of the uniform in the cache AND on the GPU.
  36470. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36471. * @param {number[]|Float32Array} data Flattened data
  36472. */
  36473. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36474. this.updateUniform(uniformName, data, data.length);
  36475. this.update();
  36476. };
  36477. /**
  36478. * Binds this uniform buffer to an effect.
  36479. * @param {Effect} effect
  36480. * @param {string} name Name of the uniform block in the shader.
  36481. */
  36482. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36483. this._currentEffect = effect;
  36484. if (this._noUBO || !this._buffer) {
  36485. return;
  36486. }
  36487. effect.bindUniformBuffer(this._buffer, name);
  36488. };
  36489. /**
  36490. * Disposes the uniform buffer.
  36491. */
  36492. UniformBuffer.prototype.dispose = function () {
  36493. if (this._noUBO) {
  36494. return;
  36495. }
  36496. var index = this._engine._uniformBuffers.indexOf(this);
  36497. if (index !== -1) {
  36498. this._engine._uniformBuffers.splice(index, 1);
  36499. }
  36500. if (!this._buffer) {
  36501. return;
  36502. }
  36503. if (this._engine._releaseBuffer(this._buffer)) {
  36504. this._buffer = null;
  36505. }
  36506. };
  36507. // Pool for avoiding memory leaks
  36508. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36509. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36510. return UniformBuffer;
  36511. }());
  36512. BABYLON.UniformBuffer = UniformBuffer;
  36513. })(BABYLON || (BABYLON = {}));
  36514. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36515. var BABYLON;
  36516. (function (BABYLON) {
  36517. /**
  36518. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36519. */
  36520. var VertexData = /** @class */ (function () {
  36521. function VertexData() {
  36522. }
  36523. /**
  36524. * Uses the passed data array to set the set the values for the specified kind of data
  36525. * @param data a linear array of floating numbers
  36526. * @param kind the type of data that is being set, eg positions, colors etc
  36527. */
  36528. VertexData.prototype.set = function (data, kind) {
  36529. switch (kind) {
  36530. case BABYLON.VertexBuffer.PositionKind:
  36531. this.positions = data;
  36532. break;
  36533. case BABYLON.VertexBuffer.NormalKind:
  36534. this.normals = data;
  36535. break;
  36536. case BABYLON.VertexBuffer.TangentKind:
  36537. this.tangents = data;
  36538. break;
  36539. case BABYLON.VertexBuffer.UVKind:
  36540. this.uvs = data;
  36541. break;
  36542. case BABYLON.VertexBuffer.UV2Kind:
  36543. this.uvs2 = data;
  36544. break;
  36545. case BABYLON.VertexBuffer.UV3Kind:
  36546. this.uvs3 = data;
  36547. break;
  36548. case BABYLON.VertexBuffer.UV4Kind:
  36549. this.uvs4 = data;
  36550. break;
  36551. case BABYLON.VertexBuffer.UV5Kind:
  36552. this.uvs5 = data;
  36553. break;
  36554. case BABYLON.VertexBuffer.UV6Kind:
  36555. this.uvs6 = data;
  36556. break;
  36557. case BABYLON.VertexBuffer.ColorKind:
  36558. this.colors = data;
  36559. break;
  36560. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36561. this.matricesIndices = data;
  36562. break;
  36563. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36564. this.matricesWeights = data;
  36565. break;
  36566. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36567. this.matricesIndicesExtra = data;
  36568. break;
  36569. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36570. this.matricesWeightsExtra = data;
  36571. break;
  36572. }
  36573. };
  36574. /**
  36575. * Associates the vertexData to the passed Mesh.
  36576. * Sets it as updatable or not (default `false`)
  36577. * @param mesh the mesh the vertexData is applied to
  36578. * @param updatable when used and having the value true allows new data to update the vertexData
  36579. * @returns the VertexData
  36580. */
  36581. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36582. this._applyTo(mesh, updatable);
  36583. return this;
  36584. };
  36585. /**
  36586. * Associates the vertexData to the passed Geometry.
  36587. * Sets it as updatable or not (default `false`)
  36588. * @param geometry the geometry the vertexData is applied to
  36589. * @param updatable when used and having the value true allows new data to update the vertexData
  36590. * @returns VertexData
  36591. */
  36592. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36593. this._applyTo(geometry, updatable);
  36594. return this;
  36595. };
  36596. /**
  36597. * Updates the associated mesh
  36598. * @param mesh the mesh to be updated
  36599. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36600. * @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
  36601. * @returns VertexData
  36602. */
  36603. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36604. this._update(mesh);
  36605. return this;
  36606. };
  36607. /**
  36608. * Updates the associated geometry
  36609. * @param geometry the geometry to be updated
  36610. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36611. * @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
  36612. * @returns VertexData.
  36613. */
  36614. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36615. this._update(geometry);
  36616. return this;
  36617. };
  36618. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36619. if (updatable === void 0) { updatable = false; }
  36620. if (this.positions) {
  36621. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36622. }
  36623. if (this.normals) {
  36624. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36625. }
  36626. if (this.tangents) {
  36627. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36628. }
  36629. if (this.uvs) {
  36630. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36631. }
  36632. if (this.uvs2) {
  36633. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36634. }
  36635. if (this.uvs3) {
  36636. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36637. }
  36638. if (this.uvs4) {
  36639. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36640. }
  36641. if (this.uvs5) {
  36642. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36643. }
  36644. if (this.uvs6) {
  36645. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36646. }
  36647. if (this.colors) {
  36648. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36649. }
  36650. if (this.matricesIndices) {
  36651. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36652. }
  36653. if (this.matricesWeights) {
  36654. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36655. }
  36656. if (this.matricesIndicesExtra) {
  36657. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36658. }
  36659. if (this.matricesWeightsExtra) {
  36660. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36661. }
  36662. if (this.indices) {
  36663. meshOrGeometry.setIndices(this.indices, null, updatable);
  36664. }
  36665. else {
  36666. meshOrGeometry.setIndices([], null);
  36667. }
  36668. return this;
  36669. };
  36670. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36671. if (this.positions) {
  36672. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36673. }
  36674. if (this.normals) {
  36675. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36676. }
  36677. if (this.tangents) {
  36678. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36679. }
  36680. if (this.uvs) {
  36681. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36682. }
  36683. if (this.uvs2) {
  36684. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36685. }
  36686. if (this.uvs3) {
  36687. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36688. }
  36689. if (this.uvs4) {
  36690. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36691. }
  36692. if (this.uvs5) {
  36693. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36694. }
  36695. if (this.uvs6) {
  36696. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36697. }
  36698. if (this.colors) {
  36699. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36700. }
  36701. if (this.matricesIndices) {
  36702. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36703. }
  36704. if (this.matricesWeights) {
  36705. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36706. }
  36707. if (this.matricesIndicesExtra) {
  36708. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36709. }
  36710. if (this.matricesWeightsExtra) {
  36711. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36712. }
  36713. if (this.indices) {
  36714. meshOrGeometry.setIndices(this.indices, null);
  36715. }
  36716. return this;
  36717. };
  36718. /**
  36719. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36720. * @param matrix the transforming matrix
  36721. * @returns the VertexData
  36722. */
  36723. VertexData.prototype.transform = function (matrix) {
  36724. var transformed = BABYLON.Vector3.Zero();
  36725. var index;
  36726. if (this.positions) {
  36727. var position = BABYLON.Vector3.Zero();
  36728. for (index = 0; index < this.positions.length; index += 3) {
  36729. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36730. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36731. this.positions[index] = transformed.x;
  36732. this.positions[index + 1] = transformed.y;
  36733. this.positions[index + 2] = transformed.z;
  36734. }
  36735. }
  36736. if (this.normals) {
  36737. var normal = BABYLON.Vector3.Zero();
  36738. for (index = 0; index < this.normals.length; index += 3) {
  36739. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36740. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36741. this.normals[index] = transformed.x;
  36742. this.normals[index + 1] = transformed.y;
  36743. this.normals[index + 2] = transformed.z;
  36744. }
  36745. }
  36746. if (this.tangents) {
  36747. var tangent = BABYLON.Vector4.Zero();
  36748. var tangentTransformed = BABYLON.Vector4.Zero();
  36749. for (index = 0; index < this.tangents.length; index += 4) {
  36750. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36751. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36752. this.tangents[index] = tangentTransformed.x;
  36753. this.tangents[index + 1] = tangentTransformed.y;
  36754. this.tangents[index + 2] = tangentTransformed.z;
  36755. this.tangents[index + 3] = tangentTransformed.w;
  36756. }
  36757. }
  36758. return this;
  36759. };
  36760. /**
  36761. * Merges the passed VertexData into the current one
  36762. * @param other the VertexData to be merged into the current one
  36763. * @returns the modified VertexData
  36764. */
  36765. VertexData.prototype.merge = function (other) {
  36766. this._validate();
  36767. other._validate();
  36768. if (!this.normals !== !other.normals ||
  36769. !this.tangents !== !other.tangents ||
  36770. !this.uvs !== !other.uvs ||
  36771. !this.uvs2 !== !other.uvs2 ||
  36772. !this.uvs3 !== !other.uvs3 ||
  36773. !this.uvs4 !== !other.uvs4 ||
  36774. !this.uvs5 !== !other.uvs5 ||
  36775. !this.uvs6 !== !other.uvs6 ||
  36776. !this.colors !== !other.colors ||
  36777. !this.matricesIndices !== !other.matricesIndices ||
  36778. !this.matricesWeights !== !other.matricesWeights ||
  36779. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36780. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36781. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36782. }
  36783. if (other.indices) {
  36784. if (!this.indices) {
  36785. this.indices = [];
  36786. }
  36787. var offset = this.positions ? this.positions.length / 3 : 0;
  36788. for (var index = 0; index < other.indices.length; index++) {
  36789. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36790. this.indices.push(other.indices[index] + offset);
  36791. }
  36792. }
  36793. this.positions = this._mergeElement(this.positions, other.positions);
  36794. this.normals = this._mergeElement(this.normals, other.normals);
  36795. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36796. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36797. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36798. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36799. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36800. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36801. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36802. this.colors = this._mergeElement(this.colors, other.colors);
  36803. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36804. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36805. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36806. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36807. return this;
  36808. };
  36809. VertexData.prototype._mergeElement = function (source, other) {
  36810. if (!source) {
  36811. return other;
  36812. }
  36813. if (!other) {
  36814. return source;
  36815. }
  36816. var len = other.length + source.length;
  36817. var isSrcTypedArray = source instanceof Float32Array;
  36818. var isOthTypedArray = other instanceof Float32Array;
  36819. // use non-loop method when the source is Float32Array
  36820. if (isSrcTypedArray) {
  36821. var ret32 = new Float32Array(len);
  36822. ret32.set(source);
  36823. ret32.set(other, source.length);
  36824. return ret32;
  36825. // source is number[], when other is also use concat
  36826. }
  36827. else if (!isOthTypedArray) {
  36828. return source.concat(other);
  36829. // source is a number[], but other is a Float32Array, loop required
  36830. }
  36831. else {
  36832. var ret = source.slice(0); // copy source to a separate array
  36833. for (var i = 0, len = other.length; i < len; i++) {
  36834. ret.push(other[i]);
  36835. }
  36836. return ret;
  36837. }
  36838. };
  36839. VertexData.prototype._validate = function () {
  36840. if (!this.positions) {
  36841. throw new Error("Positions are required");
  36842. }
  36843. var getElementCount = function (kind, values) {
  36844. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36845. if ((values.length % stride) !== 0) {
  36846. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36847. }
  36848. return values.length / stride;
  36849. };
  36850. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36851. var validateElementCount = function (kind, values) {
  36852. var elementCount = getElementCount(kind, values);
  36853. if (elementCount !== positionsElementCount) {
  36854. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36855. }
  36856. };
  36857. if (this.normals)
  36858. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36859. if (this.tangents)
  36860. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36861. if (this.uvs)
  36862. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36863. if (this.uvs2)
  36864. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36865. if (this.uvs3)
  36866. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36867. if (this.uvs4)
  36868. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36869. if (this.uvs5)
  36870. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36871. if (this.uvs6)
  36872. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36873. if (this.colors)
  36874. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36875. if (this.matricesIndices)
  36876. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36877. if (this.matricesWeights)
  36878. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36879. if (this.matricesIndicesExtra)
  36880. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36881. if (this.matricesWeightsExtra)
  36882. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36883. };
  36884. /**
  36885. * Serializes the VertexData
  36886. * @returns a serialized object
  36887. */
  36888. VertexData.prototype.serialize = function () {
  36889. var serializationObject = this.serialize();
  36890. if (this.positions) {
  36891. serializationObject.positions = this.positions;
  36892. }
  36893. if (this.normals) {
  36894. serializationObject.normals = this.normals;
  36895. }
  36896. if (this.tangents) {
  36897. serializationObject.tangents = this.tangents;
  36898. }
  36899. if (this.uvs) {
  36900. serializationObject.uvs = this.uvs;
  36901. }
  36902. if (this.uvs2) {
  36903. serializationObject.uvs2 = this.uvs2;
  36904. }
  36905. if (this.uvs3) {
  36906. serializationObject.uvs3 = this.uvs3;
  36907. }
  36908. if (this.uvs4) {
  36909. serializationObject.uvs4 = this.uvs4;
  36910. }
  36911. if (this.uvs5) {
  36912. serializationObject.uvs5 = this.uvs5;
  36913. }
  36914. if (this.uvs6) {
  36915. serializationObject.uvs6 = this.uvs6;
  36916. }
  36917. if (this.colors) {
  36918. serializationObject.colors = this.colors;
  36919. }
  36920. if (this.matricesIndices) {
  36921. serializationObject.matricesIndices = this.matricesIndices;
  36922. serializationObject.matricesIndices._isExpanded = true;
  36923. }
  36924. if (this.matricesWeights) {
  36925. serializationObject.matricesWeights = this.matricesWeights;
  36926. }
  36927. if (this.matricesIndicesExtra) {
  36928. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36929. serializationObject.matricesIndicesExtra._isExpanded = true;
  36930. }
  36931. if (this.matricesWeightsExtra) {
  36932. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36933. }
  36934. serializationObject.indices = this.indices;
  36935. return serializationObject;
  36936. };
  36937. // Statics
  36938. /**
  36939. * Extracts the vertexData from a mesh
  36940. * @param mesh the mesh from which to extract the VertexData
  36941. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36942. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36943. * @returns the object VertexData associated to the passed mesh
  36944. */
  36945. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36946. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36947. };
  36948. /**
  36949. * Extracts the vertexData from the geometry
  36950. * @param geometry the geometry from which to extract the VertexData
  36951. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36952. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36953. * @returns the object VertexData associated to the passed mesh
  36954. */
  36955. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36956. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36957. };
  36958. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36959. var result = new VertexData();
  36960. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36961. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36962. }
  36963. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36964. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36965. }
  36966. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36967. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36968. }
  36969. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36970. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36971. }
  36972. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36973. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36974. }
  36975. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36976. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36977. }
  36978. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36979. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36980. }
  36981. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36982. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36983. }
  36984. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36985. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36986. }
  36987. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36988. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36989. }
  36990. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36991. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36992. }
  36993. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36994. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36995. }
  36996. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36997. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36998. }
  36999. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37000. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37001. }
  37002. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37003. return result;
  37004. };
  37005. /**
  37006. * Creates the VertexData for a Ribbon
  37007. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37008. * * pathArray array of paths, each of which an array of successive Vector3
  37009. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37010. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37011. * * 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
  37012. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37013. * * 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)
  37014. * * 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)
  37015. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37016. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37017. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37018. * @returns the VertexData of the ribbon
  37019. */
  37020. VertexData.CreateRibbon = function (options) {
  37021. var pathArray = options.pathArray;
  37022. var closeArray = options.closeArray || false;
  37023. var closePath = options.closePath || false;
  37024. var invertUV = options.invertUV || false;
  37025. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37026. var offset = options.offset || defaultOffset;
  37027. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37028. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37029. var customUV = options.uvs;
  37030. var customColors = options.colors;
  37031. var positions = [];
  37032. var indices = [];
  37033. var normals = [];
  37034. var uvs = [];
  37035. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37036. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37037. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37038. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37039. var minlg; // minimal length among all paths from pathArray
  37040. var lg = []; // array of path lengths : nb of vertex per path
  37041. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37042. var p; // path iterator
  37043. var i; // point iterator
  37044. var j; // point iterator
  37045. // if single path in pathArray
  37046. if (pathArray.length < 2) {
  37047. var ar1 = [];
  37048. var ar2 = [];
  37049. for (i = 0; i < pathArray[0].length - offset; i++) {
  37050. ar1.push(pathArray[0][i]);
  37051. ar2.push(pathArray[0][i + offset]);
  37052. }
  37053. pathArray = [ar1, ar2];
  37054. }
  37055. // positions and horizontal distances (u)
  37056. var idc = 0;
  37057. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37058. var path;
  37059. var l;
  37060. minlg = pathArray[0].length;
  37061. var vectlg;
  37062. var dist;
  37063. for (p = 0; p < pathArray.length; p++) {
  37064. uTotalDistance[p] = 0;
  37065. us[p] = [0];
  37066. path = pathArray[p];
  37067. l = path.length;
  37068. minlg = (minlg < l) ? minlg : l;
  37069. j = 0;
  37070. while (j < l) {
  37071. positions.push(path[j].x, path[j].y, path[j].z);
  37072. if (j > 0) {
  37073. vectlg = path[j].subtract(path[j - 1]).length();
  37074. dist = vectlg + uTotalDistance[p];
  37075. us[p].push(dist);
  37076. uTotalDistance[p] = dist;
  37077. }
  37078. j++;
  37079. }
  37080. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37081. j--;
  37082. positions.push(path[0].x, path[0].y, path[0].z);
  37083. vectlg = path[j].subtract(path[0]).length();
  37084. dist = vectlg + uTotalDistance[p];
  37085. us[p].push(dist);
  37086. uTotalDistance[p] = dist;
  37087. }
  37088. lg[p] = l + closePathCorr;
  37089. idx[p] = idc;
  37090. idc += (l + closePathCorr);
  37091. }
  37092. // vertical distances (v)
  37093. var path1;
  37094. var path2;
  37095. var vertex1 = null;
  37096. var vertex2 = null;
  37097. for (i = 0; i < minlg + closePathCorr; i++) {
  37098. vTotalDistance[i] = 0;
  37099. vs[i] = [0];
  37100. for (p = 0; p < pathArray.length - 1; p++) {
  37101. path1 = pathArray[p];
  37102. path2 = pathArray[p + 1];
  37103. if (i === minlg) { // closePath
  37104. vertex1 = path1[0];
  37105. vertex2 = path2[0];
  37106. }
  37107. else {
  37108. vertex1 = path1[i];
  37109. vertex2 = path2[i];
  37110. }
  37111. vectlg = vertex2.subtract(vertex1).length();
  37112. dist = vectlg + vTotalDistance[i];
  37113. vs[i].push(dist);
  37114. vTotalDistance[i] = dist;
  37115. }
  37116. if (closeArray && vertex2 && vertex1) {
  37117. path1 = pathArray[p];
  37118. path2 = pathArray[0];
  37119. if (i === minlg) { // closePath
  37120. vertex2 = path2[0];
  37121. }
  37122. vectlg = vertex2.subtract(vertex1).length();
  37123. dist = vectlg + vTotalDistance[i];
  37124. vTotalDistance[i] = dist;
  37125. }
  37126. }
  37127. // uvs
  37128. var u;
  37129. var v;
  37130. if (customUV) {
  37131. for (p = 0; p < customUV.length; p++) {
  37132. uvs.push(customUV[p].x, customUV[p].y);
  37133. }
  37134. }
  37135. else {
  37136. for (p = 0; p < pathArray.length; p++) {
  37137. for (i = 0; i < minlg + closePathCorr; i++) {
  37138. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37139. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37140. if (invertUV) {
  37141. uvs.push(v, u);
  37142. }
  37143. else {
  37144. uvs.push(u, v);
  37145. }
  37146. }
  37147. }
  37148. }
  37149. // indices
  37150. p = 0; // path index
  37151. var pi = 0; // positions array index
  37152. var l1 = lg[p] - 1; // path1 length
  37153. var l2 = lg[p + 1] - 1; // path2 length
  37154. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37155. var shft = idx[1] - idx[0]; // shift
  37156. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37157. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37158. // 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
  37159. indices.push(pi, pi + shft, pi + 1);
  37160. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37161. pi += 1;
  37162. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37163. p++;
  37164. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37165. shft = idx[0] - idx[p];
  37166. l1 = lg[p] - 1;
  37167. l2 = lg[0] - 1;
  37168. }
  37169. else {
  37170. shft = idx[p + 1] - idx[p];
  37171. l1 = lg[p] - 1;
  37172. l2 = lg[p + 1] - 1;
  37173. }
  37174. pi = idx[p];
  37175. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37176. }
  37177. }
  37178. // normals
  37179. VertexData.ComputeNormals(positions, indices, normals);
  37180. if (closePath) { // update both the first and last vertex normals to their average value
  37181. var indexFirst = 0;
  37182. var indexLast = 0;
  37183. for (p = 0; p < pathArray.length; p++) {
  37184. indexFirst = idx[p] * 3;
  37185. if (p + 1 < pathArray.length) {
  37186. indexLast = (idx[p + 1] - 1) * 3;
  37187. }
  37188. else {
  37189. indexLast = normals.length - 3;
  37190. }
  37191. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37192. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37193. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37194. normals[indexLast] = normals[indexFirst];
  37195. normals[indexLast + 1] = normals[indexFirst + 1];
  37196. normals[indexLast + 2] = normals[indexFirst + 2];
  37197. }
  37198. }
  37199. // sides
  37200. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37201. // Colors
  37202. var colors = null;
  37203. if (customColors) {
  37204. colors = new Float32Array(customColors.length * 4);
  37205. for (var c = 0; c < customColors.length; c++) {
  37206. colors[c * 4] = customColors[c].r;
  37207. colors[c * 4 + 1] = customColors[c].g;
  37208. colors[c * 4 + 2] = customColors[c].b;
  37209. colors[c * 4 + 3] = customColors[c].a;
  37210. }
  37211. }
  37212. // Result
  37213. var vertexData = new VertexData();
  37214. var positions32 = new Float32Array(positions);
  37215. var normals32 = new Float32Array(normals);
  37216. var uvs32 = new Float32Array(uvs);
  37217. vertexData.indices = indices;
  37218. vertexData.positions = positions32;
  37219. vertexData.normals = normals32;
  37220. vertexData.uvs = uvs32;
  37221. if (colors) {
  37222. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37223. }
  37224. if (closePath) {
  37225. vertexData._idx = idx;
  37226. }
  37227. return vertexData;
  37228. };
  37229. /**
  37230. * Creates the VertexData for a box
  37231. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37232. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37233. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37234. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37235. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37236. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37237. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37238. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37239. * * 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)
  37240. * * 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)
  37241. * @returns the VertexData of the box
  37242. */
  37243. VertexData.CreateBox = function (options) {
  37244. var normalsSource = [
  37245. new BABYLON.Vector3(0, 0, 1),
  37246. new BABYLON.Vector3(0, 0, -1),
  37247. new BABYLON.Vector3(1, 0, 0),
  37248. new BABYLON.Vector3(-1, 0, 0),
  37249. new BABYLON.Vector3(0, 1, 0),
  37250. new BABYLON.Vector3(0, -1, 0)
  37251. ];
  37252. var indices = [];
  37253. var positions = [];
  37254. var normals = [];
  37255. var uvs = [];
  37256. var width = options.width || options.size || 1;
  37257. var height = options.height || options.size || 1;
  37258. var depth = options.depth || options.size || 1;
  37259. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37260. var faceUV = options.faceUV || new Array(6);
  37261. var faceColors = options.faceColors;
  37262. var colors = [];
  37263. // default face colors and UV if undefined
  37264. for (var f = 0; f < 6; f++) {
  37265. if (faceUV[f] === undefined) {
  37266. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37267. }
  37268. if (faceColors && faceColors[f] === undefined) {
  37269. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37270. }
  37271. }
  37272. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37273. // Create each face in turn.
  37274. for (var index = 0; index < normalsSource.length; index++) {
  37275. var normal = normalsSource[index];
  37276. // Get two vectors perpendicular to the face normal and to each other.
  37277. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37278. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37279. // Six indices (two triangles) per face.
  37280. var verticesLength = positions.length / 3;
  37281. indices.push(verticesLength);
  37282. indices.push(verticesLength + 1);
  37283. indices.push(verticesLength + 2);
  37284. indices.push(verticesLength);
  37285. indices.push(verticesLength + 2);
  37286. indices.push(verticesLength + 3);
  37287. // Four vertices per face.
  37288. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37289. positions.push(vertex.x, vertex.y, vertex.z);
  37290. normals.push(normal.x, normal.y, normal.z);
  37291. uvs.push(faceUV[index].z, faceUV[index].w);
  37292. if (faceColors) {
  37293. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37294. }
  37295. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37296. positions.push(vertex.x, vertex.y, vertex.z);
  37297. normals.push(normal.x, normal.y, normal.z);
  37298. uvs.push(faceUV[index].x, faceUV[index].w);
  37299. if (faceColors) {
  37300. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37301. }
  37302. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37303. positions.push(vertex.x, vertex.y, vertex.z);
  37304. normals.push(normal.x, normal.y, normal.z);
  37305. uvs.push(faceUV[index].x, faceUV[index].y);
  37306. if (faceColors) {
  37307. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37308. }
  37309. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37310. positions.push(vertex.x, vertex.y, vertex.z);
  37311. normals.push(normal.x, normal.y, normal.z);
  37312. uvs.push(faceUV[index].z, faceUV[index].y);
  37313. if (faceColors) {
  37314. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37315. }
  37316. }
  37317. // sides
  37318. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37319. // Result
  37320. var vertexData = new VertexData();
  37321. vertexData.indices = indices;
  37322. vertexData.positions = positions;
  37323. vertexData.normals = normals;
  37324. vertexData.uvs = uvs;
  37325. if (faceColors) {
  37326. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37327. vertexData.colors = totalColors;
  37328. }
  37329. return vertexData;
  37330. };
  37331. /**
  37332. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37333. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37334. * * segments sets the number of horizontal strips optional, default 32
  37335. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37336. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37337. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37338. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37339. * * 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
  37340. * * 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
  37341. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37342. * * 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)
  37343. * * 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)
  37344. * @returns the VertexData of the ellipsoid
  37345. */
  37346. VertexData.CreateSphere = function (options) {
  37347. var segments = options.segments || 32;
  37348. var diameterX = options.diameterX || options.diameter || 1;
  37349. var diameterY = options.diameterY || options.diameter || 1;
  37350. var diameterZ = options.diameterZ || options.diameter || 1;
  37351. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37352. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37353. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37354. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37355. var totalZRotationSteps = 2 + segments;
  37356. var totalYRotationSteps = 2 * totalZRotationSteps;
  37357. var indices = [];
  37358. var positions = [];
  37359. var normals = [];
  37360. var uvs = [];
  37361. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37362. var normalizedZ = zRotationStep / totalZRotationSteps;
  37363. var angleZ = normalizedZ * Math.PI * slice;
  37364. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37365. var normalizedY = yRotationStep / totalYRotationSteps;
  37366. var angleY = normalizedY * Math.PI * 2 * arc;
  37367. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37368. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37369. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37370. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37371. var vertex = complete.multiply(radius);
  37372. var normal = complete.divide(radius).normalize();
  37373. positions.push(vertex.x, vertex.y, vertex.z);
  37374. normals.push(normal.x, normal.y, normal.z);
  37375. uvs.push(normalizedY, normalizedZ);
  37376. }
  37377. if (zRotationStep > 0) {
  37378. var verticesCount = positions.length / 3;
  37379. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37380. indices.push((firstIndex));
  37381. indices.push((firstIndex + 1));
  37382. indices.push(firstIndex + totalYRotationSteps + 1);
  37383. indices.push((firstIndex + totalYRotationSteps + 1));
  37384. indices.push((firstIndex + 1));
  37385. indices.push((firstIndex + totalYRotationSteps + 2));
  37386. }
  37387. }
  37388. }
  37389. // Sides
  37390. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37391. // Result
  37392. var vertexData = new VertexData();
  37393. vertexData.indices = indices;
  37394. vertexData.positions = positions;
  37395. vertexData.normals = normals;
  37396. vertexData.uvs = uvs;
  37397. return vertexData;
  37398. };
  37399. /**
  37400. * Creates the VertexData for a cylinder, cone or prism
  37401. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37402. * * height sets the height (y direction) of the cylinder, optional, default 2
  37403. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37404. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37405. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37406. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37407. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37408. * * 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
  37409. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37410. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37411. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37412. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37413. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37414. * * 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)
  37415. * * 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)
  37416. * @returns the VertexData of the cylinder, cone or prism
  37417. */
  37418. VertexData.CreateCylinder = function (options) {
  37419. var height = options.height || 2;
  37420. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37421. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37422. var tessellation = options.tessellation || 24;
  37423. var subdivisions = options.subdivisions || 1;
  37424. var hasRings = options.hasRings ? true : false;
  37425. var enclose = options.enclose ? true : false;
  37426. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37427. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37428. var faceUV = options.faceUV || new Array(3);
  37429. var faceColors = options.faceColors;
  37430. // default face colors and UV if undefined
  37431. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37432. var ringNb = (hasRings) ? subdivisions : 1;
  37433. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37434. var f;
  37435. for (f = 0; f < surfaceNb; f++) {
  37436. if (faceColors && faceColors[f] === undefined) {
  37437. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37438. }
  37439. }
  37440. for (f = 0; f < surfaceNb; f++) {
  37441. if (faceUV && faceUV[f] === undefined) {
  37442. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37443. }
  37444. }
  37445. var indices = new Array();
  37446. var positions = new Array();
  37447. var normals = new Array();
  37448. var uvs = new Array();
  37449. var colors = new Array();
  37450. var angle_step = Math.PI * 2 * arc / tessellation;
  37451. var angle;
  37452. var h;
  37453. var radius;
  37454. var tan = (diameterBottom - diameterTop) / 2 / height;
  37455. var ringVertex = BABYLON.Vector3.Zero();
  37456. var ringNormal = BABYLON.Vector3.Zero();
  37457. var ringFirstVertex = BABYLON.Vector3.Zero();
  37458. var ringFirstNormal = BABYLON.Vector3.Zero();
  37459. var quadNormal = BABYLON.Vector3.Zero();
  37460. var Y = BABYLON.Axis.Y;
  37461. // positions, normals, uvs
  37462. var i;
  37463. var j;
  37464. var r;
  37465. var ringIdx = 1;
  37466. var s = 1; // surface index
  37467. var cs = 0;
  37468. var v = 0;
  37469. for (i = 0; i <= subdivisions; i++) {
  37470. h = i / subdivisions;
  37471. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37472. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37473. for (r = 0; r < ringIdx; r++) {
  37474. if (hasRings) {
  37475. s += r;
  37476. }
  37477. if (enclose) {
  37478. s += 2 * r;
  37479. }
  37480. for (j = 0; j <= tessellation; j++) {
  37481. angle = j * angle_step;
  37482. // position
  37483. ringVertex.x = Math.cos(-angle) * radius;
  37484. ringVertex.y = -height / 2 + h * height;
  37485. ringVertex.z = Math.sin(-angle) * radius;
  37486. // normal
  37487. if (diameterTop === 0 && i === subdivisions) {
  37488. // if no top cap, reuse former normals
  37489. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37490. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37491. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37492. }
  37493. else {
  37494. ringNormal.x = ringVertex.x;
  37495. ringNormal.z = ringVertex.z;
  37496. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37497. ringNormal.normalize();
  37498. }
  37499. // keep first ring vertex values for enclose
  37500. if (j === 0) {
  37501. ringFirstVertex.copyFrom(ringVertex);
  37502. ringFirstNormal.copyFrom(ringNormal);
  37503. }
  37504. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37505. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37506. if (hasRings) {
  37507. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37508. }
  37509. else {
  37510. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37511. }
  37512. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37513. if (faceColors) {
  37514. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37515. }
  37516. }
  37517. // if enclose, add four vertices and their dedicated normals
  37518. if (arc !== 1 && enclose) {
  37519. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37520. positions.push(0, ringVertex.y, 0);
  37521. positions.push(0, ringVertex.y, 0);
  37522. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37523. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37524. quadNormal.normalize();
  37525. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37526. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37527. quadNormal.normalize();
  37528. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37529. if (hasRings) {
  37530. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37531. }
  37532. else {
  37533. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37534. }
  37535. uvs.push(faceUV[s + 1].x, v);
  37536. uvs.push(faceUV[s + 1].z, v);
  37537. if (hasRings) {
  37538. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37539. }
  37540. else {
  37541. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37542. }
  37543. uvs.push(faceUV[s + 2].x, v);
  37544. uvs.push(faceUV[s + 2].z, v);
  37545. if (faceColors) {
  37546. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37547. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37548. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37549. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37550. }
  37551. }
  37552. if (cs !== s) {
  37553. cs = s;
  37554. }
  37555. }
  37556. }
  37557. // indices
  37558. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37559. var s;
  37560. i = 0;
  37561. for (s = 0; s < subdivisions; s++) {
  37562. var i0 = 0;
  37563. var i1 = 0;
  37564. var i2 = 0;
  37565. var i3 = 0;
  37566. for (j = 0; j < tessellation; j++) {
  37567. i0 = i * (e + 1) + j;
  37568. i1 = (i + 1) * (e + 1) + j;
  37569. i2 = i * (e + 1) + (j + 1);
  37570. i3 = (i + 1) * (e + 1) + (j + 1);
  37571. indices.push(i0, i1, i2);
  37572. indices.push(i3, i2, i1);
  37573. }
  37574. if (arc !== 1 && enclose) { // if enclose, add two quads
  37575. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37576. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37577. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37578. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37579. }
  37580. i = (hasRings) ? (i + 2) : (i + 1);
  37581. }
  37582. // Caps
  37583. var createCylinderCap = function (isTop) {
  37584. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37585. if (radius === 0) {
  37586. return;
  37587. }
  37588. // Cap positions, normals & uvs
  37589. var angle;
  37590. var circleVector;
  37591. var i;
  37592. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37593. var c = null;
  37594. if (faceColors) {
  37595. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37596. }
  37597. // cap center
  37598. var vbase = positions.length / 3;
  37599. var offset = isTop ? height / 2 : -height / 2;
  37600. var center = new BABYLON.Vector3(0, offset, 0);
  37601. positions.push(center.x, center.y, center.z);
  37602. normals.push(0, isTop ? 1 : -1, 0);
  37603. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37604. if (c) {
  37605. colors.push(c.r, c.g, c.b, c.a);
  37606. }
  37607. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37608. for (i = 0; i <= tessellation; i++) {
  37609. angle = Math.PI * 2 * i * arc / tessellation;
  37610. var cos = Math.cos(-angle);
  37611. var sin = Math.sin(-angle);
  37612. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37613. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37614. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37615. normals.push(0, isTop ? 1 : -1, 0);
  37616. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37617. if (c) {
  37618. colors.push(c.r, c.g, c.b, c.a);
  37619. }
  37620. }
  37621. // Cap indices
  37622. for (i = 0; i < tessellation; i++) {
  37623. if (!isTop) {
  37624. indices.push(vbase);
  37625. indices.push(vbase + (i + 1));
  37626. indices.push(vbase + (i + 2));
  37627. }
  37628. else {
  37629. indices.push(vbase);
  37630. indices.push(vbase + (i + 2));
  37631. indices.push(vbase + (i + 1));
  37632. }
  37633. }
  37634. };
  37635. // add caps to geometry
  37636. createCylinderCap(false);
  37637. createCylinderCap(true);
  37638. // Sides
  37639. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37640. var vertexData = new VertexData();
  37641. vertexData.indices = indices;
  37642. vertexData.positions = positions;
  37643. vertexData.normals = normals;
  37644. vertexData.uvs = uvs;
  37645. if (faceColors) {
  37646. vertexData.colors = colors;
  37647. }
  37648. return vertexData;
  37649. };
  37650. /**
  37651. * Creates the VertexData for a torus
  37652. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37653. * * diameter the diameter of the torus, optional default 1
  37654. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37655. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37656. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37657. * * 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)
  37658. * * 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)
  37659. * @returns the VertexData of the torus
  37660. */
  37661. VertexData.CreateTorus = function (options) {
  37662. var indices = [];
  37663. var positions = [];
  37664. var normals = [];
  37665. var uvs = [];
  37666. var diameter = options.diameter || 1;
  37667. var thickness = options.thickness || 0.5;
  37668. var tessellation = options.tessellation || 16;
  37669. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37670. var stride = tessellation + 1;
  37671. for (var i = 0; i <= tessellation; i++) {
  37672. var u = i / tessellation;
  37673. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37674. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37675. for (var j = 0; j <= tessellation; j++) {
  37676. var v = 1 - j / tessellation;
  37677. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37678. var dx = Math.cos(innerAngle);
  37679. var dy = Math.sin(innerAngle);
  37680. // Create a vertex.
  37681. var normal = new BABYLON.Vector3(dx, dy, 0);
  37682. var position = normal.scale(thickness / 2);
  37683. var textureCoordinate = new BABYLON.Vector2(u, v);
  37684. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37685. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37686. positions.push(position.x, position.y, position.z);
  37687. normals.push(normal.x, normal.y, normal.z);
  37688. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37689. // And create indices for two triangles.
  37690. var nextI = (i + 1) % stride;
  37691. var nextJ = (j + 1) % stride;
  37692. indices.push(i * stride + j);
  37693. indices.push(i * stride + nextJ);
  37694. indices.push(nextI * stride + j);
  37695. indices.push(i * stride + nextJ);
  37696. indices.push(nextI * stride + nextJ);
  37697. indices.push(nextI * stride + j);
  37698. }
  37699. }
  37700. // Sides
  37701. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37702. // Result
  37703. var vertexData = new VertexData();
  37704. vertexData.indices = indices;
  37705. vertexData.positions = positions;
  37706. vertexData.normals = normals;
  37707. vertexData.uvs = uvs;
  37708. return vertexData;
  37709. };
  37710. /**
  37711. * Creates the VertexData of the LineSystem
  37712. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37713. * - lines an array of lines, each line being an array of successive Vector3
  37714. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37715. * @returns the VertexData of the LineSystem
  37716. */
  37717. VertexData.CreateLineSystem = function (options) {
  37718. var indices = [];
  37719. var positions = [];
  37720. var lines = options.lines;
  37721. var colors = options.colors;
  37722. var vertexColors = [];
  37723. var idx = 0;
  37724. for (var l = 0; l < lines.length; l++) {
  37725. var points = lines[l];
  37726. for (var index = 0; index < points.length; index++) {
  37727. positions.push(points[index].x, points[index].y, points[index].z);
  37728. if (colors) {
  37729. var color = colors[l];
  37730. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37731. }
  37732. if (index > 0) {
  37733. indices.push(idx - 1);
  37734. indices.push(idx);
  37735. }
  37736. idx++;
  37737. }
  37738. }
  37739. var vertexData = new VertexData();
  37740. vertexData.indices = indices;
  37741. vertexData.positions = positions;
  37742. if (colors) {
  37743. vertexData.colors = vertexColors;
  37744. }
  37745. return vertexData;
  37746. };
  37747. /**
  37748. * Create the VertexData for a DashedLines
  37749. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37750. * - points an array successive Vector3
  37751. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37752. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37753. * - dashNb the intended total number of dashes, optional, default 200
  37754. * @returns the VertexData for the DashedLines
  37755. */
  37756. VertexData.CreateDashedLines = function (options) {
  37757. var dashSize = options.dashSize || 3;
  37758. var gapSize = options.gapSize || 1;
  37759. var dashNb = options.dashNb || 200;
  37760. var points = options.points;
  37761. var positions = new Array();
  37762. var indices = new Array();
  37763. var curvect = BABYLON.Vector3.Zero();
  37764. var lg = 0;
  37765. var nb = 0;
  37766. var shft = 0;
  37767. var dashshft = 0;
  37768. var curshft = 0;
  37769. var idx = 0;
  37770. var i = 0;
  37771. for (i = 0; i < points.length - 1; i++) {
  37772. points[i + 1].subtractToRef(points[i], curvect);
  37773. lg += curvect.length();
  37774. }
  37775. shft = lg / dashNb;
  37776. dashshft = dashSize * shft / (dashSize + gapSize);
  37777. for (i = 0; i < points.length - 1; i++) {
  37778. points[i + 1].subtractToRef(points[i], curvect);
  37779. nb = Math.floor(curvect.length() / shft);
  37780. curvect.normalize();
  37781. for (var j = 0; j < nb; j++) {
  37782. curshft = shft * j;
  37783. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37784. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37785. indices.push(idx, idx + 1);
  37786. idx += 2;
  37787. }
  37788. }
  37789. // Result
  37790. var vertexData = new VertexData();
  37791. vertexData.positions = positions;
  37792. vertexData.indices = indices;
  37793. return vertexData;
  37794. };
  37795. /**
  37796. * Creates the VertexData for a Ground
  37797. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37798. * - width the width (x direction) of the ground, optional, default 1
  37799. * - height the height (z direction) of the ground, optional, default 1
  37800. * - subdivisions the number of subdivisions per side, optional, default 1
  37801. * @returns the VertexData of the Ground
  37802. */
  37803. VertexData.CreateGround = function (options) {
  37804. var indices = [];
  37805. var positions = [];
  37806. var normals = [];
  37807. var uvs = [];
  37808. var row, col;
  37809. var width = options.width || 1;
  37810. var height = options.height || 1;
  37811. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37812. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37813. for (row = 0; row <= subdivisionsY; row++) {
  37814. for (col = 0; col <= subdivisionsX; col++) {
  37815. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37816. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37817. positions.push(position.x, position.y, position.z);
  37818. normals.push(normal.x, normal.y, normal.z);
  37819. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37820. }
  37821. }
  37822. for (row = 0; row < subdivisionsY; row++) {
  37823. for (col = 0; col < subdivisionsX; col++) {
  37824. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37825. indices.push(col + 1 + row * (subdivisionsX + 1));
  37826. indices.push(col + row * (subdivisionsX + 1));
  37827. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37828. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37829. indices.push(col + row * (subdivisionsX + 1));
  37830. }
  37831. }
  37832. // Result
  37833. var vertexData = new VertexData();
  37834. vertexData.indices = indices;
  37835. vertexData.positions = positions;
  37836. vertexData.normals = normals;
  37837. vertexData.uvs = uvs;
  37838. return vertexData;
  37839. };
  37840. /**
  37841. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37842. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37843. * * xmin the ground minimum X coordinate, optional, default -1
  37844. * * zmin the ground minimum Z coordinate, optional, default -1
  37845. * * xmax the ground maximum X coordinate, optional, default 1
  37846. * * zmax the ground maximum Z coordinate, optional, default 1
  37847. * * 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}
  37848. * * 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}
  37849. * @returns the VertexData of the TiledGround
  37850. */
  37851. VertexData.CreateTiledGround = function (options) {
  37852. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37853. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37854. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37855. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37856. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37857. var precision = options.precision || { w: 1, h: 1 };
  37858. var indices = new Array();
  37859. var positions = new Array();
  37860. var normals = new Array();
  37861. var uvs = new Array();
  37862. var row, col, tileRow, tileCol;
  37863. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37864. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37865. precision.w = (precision.w < 1) ? 1 : precision.w;
  37866. precision.h = (precision.h < 1) ? 1 : precision.h;
  37867. var tileSize = {
  37868. 'w': (xmax - xmin) / subdivisions.w,
  37869. 'h': (zmax - zmin) / subdivisions.h
  37870. };
  37871. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37872. // Indices
  37873. var base = positions.length / 3;
  37874. var rowLength = precision.w + 1;
  37875. for (row = 0; row < precision.h; row++) {
  37876. for (col = 0; col < precision.w; col++) {
  37877. var square = [
  37878. base + col + row * rowLength,
  37879. base + (col + 1) + row * rowLength,
  37880. base + (col + 1) + (row + 1) * rowLength,
  37881. base + col + (row + 1) * rowLength
  37882. ];
  37883. indices.push(square[1]);
  37884. indices.push(square[2]);
  37885. indices.push(square[3]);
  37886. indices.push(square[0]);
  37887. indices.push(square[1]);
  37888. indices.push(square[3]);
  37889. }
  37890. }
  37891. // Position, normals and uvs
  37892. var position = BABYLON.Vector3.Zero();
  37893. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37894. for (row = 0; row <= precision.h; row++) {
  37895. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37896. for (col = 0; col <= precision.w; col++) {
  37897. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37898. position.y = 0;
  37899. positions.push(position.x, position.y, position.z);
  37900. normals.push(normal.x, normal.y, normal.z);
  37901. uvs.push(col / precision.w, row / precision.h);
  37902. }
  37903. }
  37904. }
  37905. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37906. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37907. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37908. }
  37909. }
  37910. // Result
  37911. var vertexData = new VertexData();
  37912. vertexData.indices = indices;
  37913. vertexData.positions = positions;
  37914. vertexData.normals = normals;
  37915. vertexData.uvs = uvs;
  37916. return vertexData;
  37917. };
  37918. /**
  37919. * Creates the VertexData of the Ground designed from a heightmap
  37920. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37921. * * width the width (x direction) of the ground
  37922. * * height the height (z direction) of the ground
  37923. * * subdivisions the number of subdivisions per side
  37924. * * minHeight the minimum altitude on the ground, optional, default 0
  37925. * * maxHeight the maximum altitude on the ground, optional default 1
  37926. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37927. * * buffer the array holding the image color data
  37928. * * bufferWidth the width of image
  37929. * * bufferHeight the height of image
  37930. * @returns the VertexData of the Ground designed from a heightmap
  37931. */
  37932. VertexData.CreateGroundFromHeightMap = function (options) {
  37933. var indices = [];
  37934. var positions = [];
  37935. var normals = [];
  37936. var uvs = [];
  37937. var row, col;
  37938. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37939. // Vertices
  37940. for (row = 0; row <= options.subdivisions; row++) {
  37941. for (col = 0; col <= options.subdivisions; col++) {
  37942. 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));
  37943. // Compute height
  37944. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37945. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37946. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37947. var r = options.buffer[pos] / 255.0;
  37948. var g = options.buffer[pos + 1] / 255.0;
  37949. var b = options.buffer[pos + 2] / 255.0;
  37950. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37951. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37952. // Add vertex
  37953. positions.push(position.x, position.y, position.z);
  37954. normals.push(0, 0, 0);
  37955. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37956. }
  37957. }
  37958. // Indices
  37959. for (row = 0; row < options.subdivisions; row++) {
  37960. for (col = 0; col < options.subdivisions; col++) {
  37961. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37962. indices.push(col + 1 + row * (options.subdivisions + 1));
  37963. indices.push(col + row * (options.subdivisions + 1));
  37964. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37965. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37966. indices.push(col + row * (options.subdivisions + 1));
  37967. }
  37968. }
  37969. // Normals
  37970. VertexData.ComputeNormals(positions, indices, normals);
  37971. // Result
  37972. var vertexData = new VertexData();
  37973. vertexData.indices = indices;
  37974. vertexData.positions = positions;
  37975. vertexData.normals = normals;
  37976. vertexData.uvs = uvs;
  37977. return vertexData;
  37978. };
  37979. /**
  37980. * Creates the VertexData for a Plane
  37981. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37982. * * size sets the width and height of the plane to the value of size, optional default 1
  37983. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37984. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37985. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37986. * * 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)
  37987. * * 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)
  37988. * @returns the VertexData of the box
  37989. */
  37990. VertexData.CreatePlane = function (options) {
  37991. var indices = [];
  37992. var positions = [];
  37993. var normals = [];
  37994. var uvs = [];
  37995. var width = options.width || options.size || 1;
  37996. var height = options.height || options.size || 1;
  37997. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37998. // Vertices
  37999. var halfWidth = width / 2.0;
  38000. var halfHeight = height / 2.0;
  38001. positions.push(-halfWidth, -halfHeight, 0);
  38002. normals.push(0, 0, -1.0);
  38003. uvs.push(0.0, 0.0);
  38004. positions.push(halfWidth, -halfHeight, 0);
  38005. normals.push(0, 0, -1.0);
  38006. uvs.push(1.0, 0.0);
  38007. positions.push(halfWidth, halfHeight, 0);
  38008. normals.push(0, 0, -1.0);
  38009. uvs.push(1.0, 1.0);
  38010. positions.push(-halfWidth, halfHeight, 0);
  38011. normals.push(0, 0, -1.0);
  38012. uvs.push(0.0, 1.0);
  38013. // Indices
  38014. indices.push(0);
  38015. indices.push(1);
  38016. indices.push(2);
  38017. indices.push(0);
  38018. indices.push(2);
  38019. indices.push(3);
  38020. // Sides
  38021. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38022. // Result
  38023. var vertexData = new VertexData();
  38024. vertexData.indices = indices;
  38025. vertexData.positions = positions;
  38026. vertexData.normals = normals;
  38027. vertexData.uvs = uvs;
  38028. return vertexData;
  38029. };
  38030. /**
  38031. * Creates the VertexData of the Disc or regular Polygon
  38032. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38033. * * radius the radius of the disc, optional default 0.5
  38034. * * tessellation the number of polygon sides, optional, default 64
  38035. * * 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
  38036. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38037. * * 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)
  38038. * * 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)
  38039. * @returns the VertexData of the box
  38040. */
  38041. VertexData.CreateDisc = function (options) {
  38042. var positions = new Array();
  38043. var indices = new Array();
  38044. var normals = new Array();
  38045. var uvs = new Array();
  38046. var radius = options.radius || 0.5;
  38047. var tessellation = options.tessellation || 64;
  38048. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38049. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38050. // positions and uvs
  38051. positions.push(0, 0, 0); // disc center first
  38052. uvs.push(0.5, 0.5);
  38053. var theta = Math.PI * 2 * arc;
  38054. var step = theta / tessellation;
  38055. for (var a = 0; a < theta; a += step) {
  38056. var x = Math.cos(a);
  38057. var y = Math.sin(a);
  38058. var u = (x + 1) / 2;
  38059. var v = (1 - y) / 2;
  38060. positions.push(radius * x, radius * y, 0);
  38061. uvs.push(u, v);
  38062. }
  38063. if (arc === 1) {
  38064. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38065. uvs.push(uvs[2], uvs[3]);
  38066. }
  38067. //indices
  38068. var vertexNb = positions.length / 3;
  38069. for (var i = 1; i < vertexNb - 1; i++) {
  38070. indices.push(i + 1, 0, i);
  38071. }
  38072. // result
  38073. VertexData.ComputeNormals(positions, indices, normals);
  38074. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38075. var vertexData = new VertexData();
  38076. vertexData.indices = indices;
  38077. vertexData.positions = positions;
  38078. vertexData.normals = normals;
  38079. vertexData.uvs = uvs;
  38080. return vertexData;
  38081. };
  38082. /**
  38083. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38084. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38085. * @param polygon a mesh built from polygonTriangulation.build()
  38086. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38087. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38088. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38089. * @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)
  38090. * @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)
  38091. * @returns the VertexData of the Polygon
  38092. */
  38093. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38094. var faceUV = fUV || new Array(3);
  38095. var faceColors = fColors;
  38096. var colors = [];
  38097. // default face colors and UV if undefined
  38098. for (var f = 0; f < 3; f++) {
  38099. if (faceUV[f] === undefined) {
  38100. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38101. }
  38102. if (faceColors && faceColors[f] === undefined) {
  38103. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38104. }
  38105. }
  38106. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38107. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38108. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38109. var indices = polygon.getIndices();
  38110. // set face colours and textures
  38111. var idx = 0;
  38112. var face = 0;
  38113. for (var index = 0; index < normals.length; index += 3) {
  38114. //Edge Face no. 1
  38115. if (Math.abs(normals[index + 1]) < 0.001) {
  38116. face = 1;
  38117. }
  38118. //Top Face no. 0
  38119. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38120. face = 0;
  38121. }
  38122. //Bottom Face no. 2
  38123. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38124. face = 2;
  38125. }
  38126. idx = index / 3;
  38127. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38128. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38129. if (faceColors) {
  38130. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38131. }
  38132. }
  38133. // sides
  38134. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38135. // Result
  38136. var vertexData = new VertexData();
  38137. vertexData.indices = indices;
  38138. vertexData.positions = positions;
  38139. vertexData.normals = normals;
  38140. vertexData.uvs = uvs;
  38141. if (faceColors) {
  38142. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38143. vertexData.colors = totalColors;
  38144. }
  38145. return vertexData;
  38146. };
  38147. /**
  38148. * Creates the VertexData of the IcoSphere
  38149. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38150. * * radius the radius of the IcoSphere, optional default 1
  38151. * * radiusX allows stretching in the x direction, optional, default radius
  38152. * * radiusY allows stretching in the y direction, optional, default radius
  38153. * * radiusZ allows stretching in the z direction, optional, default radius
  38154. * * flat when true creates a flat shaded mesh, optional, default true
  38155. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38156. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38157. * * 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)
  38158. * * 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)
  38159. * @returns the VertexData of the IcoSphere
  38160. */
  38161. VertexData.CreateIcoSphere = function (options) {
  38162. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38163. var radius = options.radius || 1;
  38164. var flat = (options.flat === undefined) ? true : options.flat;
  38165. var subdivisions = options.subdivisions || 4;
  38166. var radiusX = options.radiusX || radius;
  38167. var radiusY = options.radiusY || radius;
  38168. var radiusZ = options.radiusZ || radius;
  38169. var t = (1 + Math.sqrt(5)) / 2;
  38170. // 12 vertex x,y,z
  38171. var ico_vertices = [
  38172. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38173. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38174. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38175. ];
  38176. // index of 3 vertex makes a face of icopshere
  38177. var ico_indices = [
  38178. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38179. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38180. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38181. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38182. ];
  38183. // vertex for uv have aliased position, not for UV
  38184. var vertices_unalias_id = [
  38185. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38186. // vertex alias
  38187. 0,
  38188. 2,
  38189. 3,
  38190. 3,
  38191. 3,
  38192. 4,
  38193. 7,
  38194. 8,
  38195. 9,
  38196. 9,
  38197. 10,
  38198. 11 // 23: B + 12
  38199. ];
  38200. // uv as integer step (not pixels !)
  38201. var ico_vertexuv = [
  38202. 5, 1, 3, 1, 6, 4, 0, 0,
  38203. 5, 3, 4, 2, 2, 2, 4, 0,
  38204. 2, 0, 1, 1, 6, 0, 6, 2,
  38205. // vertex alias (for same vertex on different faces)
  38206. 0, 4,
  38207. 3, 3,
  38208. 4, 4,
  38209. 3, 1,
  38210. 4, 2,
  38211. 4, 4,
  38212. 0, 2,
  38213. 1, 1,
  38214. 2, 2,
  38215. 3, 3,
  38216. 1, 3,
  38217. 2, 4 // 23: B + 12
  38218. ];
  38219. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38220. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38221. // First island of uv mapping
  38222. // v = 4h 3+ 2
  38223. // v = 3h 9+ 4
  38224. // v = 2h 9+ 5 B
  38225. // v = 1h 9 1 0
  38226. // v = 0h 3 8 7 A
  38227. // u = 0 1 2 3 4 5 6 *a
  38228. // Second island of uv mapping
  38229. // v = 4h 0+ B+ 4+
  38230. // v = 3h A+ 2+
  38231. // v = 2h 7+ 6 3+
  38232. // v = 1h 8+ 3+
  38233. // v = 0h
  38234. // u = 0 1 2 3 4 5 6 *a
  38235. // Face layout on texture UV mapping
  38236. // ============
  38237. // \ 4 /\ 16 / ======
  38238. // \ / \ / /\ 11 /
  38239. // \/ 7 \/ / \ /
  38240. // ======= / 10 \/
  38241. // /\ 17 /\ =======
  38242. // / \ / \ \ 15 /\
  38243. // / 8 \/ 12 \ \ / \
  38244. // ============ \/ 6 \
  38245. // \ 18 /\ ============
  38246. // \ / \ \ 5 /\ 0 /
  38247. // \/ 13 \ \ / \ /
  38248. // ======= \/ 1 \/
  38249. // =============
  38250. // /\ 19 /\ 2 /\
  38251. // / \ / \ / \
  38252. // / 14 \/ 9 \/ 3 \
  38253. // ===================
  38254. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38255. var ustep = 138 / 1024;
  38256. var vstep = 239 / 1024;
  38257. var uoffset = 60 / 1024;
  38258. var voffset = 26 / 1024;
  38259. // Second island should have margin, not to touch the first island
  38260. // avoid any borderline artefact in pixel rounding
  38261. var island_u_offset = -40 / 1024;
  38262. var island_v_offset = +20 / 1024;
  38263. // face is either island 0 or 1 :
  38264. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38265. var island = [
  38266. 0, 0, 0, 0, 1,
  38267. 0, 0, 1, 1, 0,
  38268. 0, 0, 1, 1, 0,
  38269. 0, 1, 1, 1, 0 // 15 - 19
  38270. ];
  38271. var indices = new Array();
  38272. var positions = new Array();
  38273. var normals = new Array();
  38274. var uvs = new Array();
  38275. var current_indice = 0;
  38276. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38277. var face_vertex_pos = new Array(3);
  38278. var face_vertex_uv = new Array(3);
  38279. var v012;
  38280. for (v012 = 0; v012 < 3; v012++) {
  38281. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38282. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38283. }
  38284. // create all with normals
  38285. for (var face = 0; face < 20; face++) {
  38286. // 3 vertex per face
  38287. for (v012 = 0; v012 < 3; v012++) {
  38288. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38289. var v_id = ico_indices[3 * face + v012];
  38290. // vertex have 3D position (x,y,z)
  38291. 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]);
  38292. // Normalize to get normal, then scale to radius
  38293. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38294. // uv Coordinates from vertex ID
  38295. 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);
  38296. }
  38297. // Subdivide the face (interpolate pos, norm, uv)
  38298. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38299. // - norm is linear interpolation of vertex corner normal
  38300. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38301. // - uv is linear interpolation
  38302. //
  38303. // Topology is as below for sub-divide by 2
  38304. // vertex shown as v0,v1,v2
  38305. // interp index is i1 to progress in range [v0,v1[
  38306. // interp index is i2 to progress in range [v0,v2[
  38307. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38308. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38309. //
  38310. //
  38311. // i2 v2
  38312. // ^ ^
  38313. // / / \
  38314. // / / \
  38315. // / / \
  38316. // / / (0,1) \
  38317. // / #---------\
  38318. // / / \ (0,0)'/ \
  38319. // / / \ / \
  38320. // / / \ / \
  38321. // / / (0,0) \ / (1,0) \
  38322. // / #---------#---------\
  38323. // v0 v1
  38324. //
  38325. // --------------------> i1
  38326. //
  38327. // interp of (i1,i2):
  38328. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38329. // along i1 : lerp(x0,x1, i1/(S-i2))
  38330. //
  38331. // centroid of triangle is needed to get help normal computation
  38332. // (c1,c2) are used for centroid location
  38333. var interp_vertex = function (i1, i2, c1, c2) {
  38334. // vertex is interpolated from
  38335. // - face_vertex_pos[0..2]
  38336. // - face_vertex_uv[0..2]
  38337. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38338. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38339. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38340. pos_interp.normalize();
  38341. var vertex_normal;
  38342. if (flat) {
  38343. // in flat mode, recalculate normal as face centroid normal
  38344. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38345. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38346. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38347. }
  38348. else {
  38349. // in smooth mode, recalculate normal from each single vertex position
  38350. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38351. }
  38352. // Vertex normal need correction due to X,Y,Z radius scaling
  38353. vertex_normal.x /= radiusX;
  38354. vertex_normal.y /= radiusY;
  38355. vertex_normal.z /= radiusZ;
  38356. vertex_normal.normalize();
  38357. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38358. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38359. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38360. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38361. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38362. uvs.push(uv_interp.x, uv_interp.y);
  38363. // push each vertex has member of a face
  38364. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38365. indices.push(current_indice);
  38366. current_indice++;
  38367. };
  38368. for (var i2 = 0; i2 < subdivisions; i2++) {
  38369. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38370. // face : (i1,i2) for /\ :
  38371. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38372. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38373. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38374. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38375. if (i1 + i2 + 1 < subdivisions) {
  38376. // face : (i1,i2)' for \/ :
  38377. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38378. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38379. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38380. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38381. }
  38382. }
  38383. }
  38384. }
  38385. // Sides
  38386. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38387. // Result
  38388. var vertexData = new VertexData();
  38389. vertexData.indices = indices;
  38390. vertexData.positions = positions;
  38391. vertexData.normals = normals;
  38392. vertexData.uvs = uvs;
  38393. return vertexData;
  38394. };
  38395. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38396. /**
  38397. * Creates the VertexData for a Polyhedron
  38398. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38399. * * type provided types are:
  38400. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38401. * * 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)
  38402. * * size the size of the IcoSphere, optional default 1
  38403. * * sizeX allows stretching in the x direction, optional, default size
  38404. * * sizeY allows stretching in the y direction, optional, default size
  38405. * * sizeZ allows stretching in the z direction, optional, default size
  38406. * * 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
  38407. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38408. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38409. * * flat when true creates a flat shaded mesh, optional, default true
  38410. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38411. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38412. * * 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)
  38413. * * 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)
  38414. * @returns the VertexData of the Polyhedron
  38415. */
  38416. VertexData.CreatePolyhedron = function (options) {
  38417. // provided polyhedron types :
  38418. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38419. // 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)
  38420. var polyhedra = [];
  38421. 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]] };
  38422. 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]] };
  38423. polyhedra[2] = {
  38424. 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]],
  38425. 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]]
  38426. };
  38427. polyhedra[3] = {
  38428. 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]],
  38429. 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]]
  38430. };
  38431. polyhedra[4] = {
  38432. 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]],
  38433. 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]]
  38434. };
  38435. 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]] };
  38436. 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]] };
  38437. 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]] };
  38438. 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]] };
  38439. 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]] };
  38440. 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]] };
  38441. 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]] };
  38442. 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]] };
  38443. 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]] };
  38444. polyhedra[14] = {
  38445. 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]],
  38446. 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]]
  38447. };
  38448. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38449. var size = options.size;
  38450. var sizeX = options.sizeX || size || 1;
  38451. var sizeY = options.sizeY || size || 1;
  38452. var sizeZ = options.sizeZ || size || 1;
  38453. var data = options.custom || polyhedra[type];
  38454. var nbfaces = data.face.length;
  38455. var faceUV = options.faceUV || new Array(nbfaces);
  38456. var faceColors = options.faceColors;
  38457. var flat = (options.flat === undefined) ? true : options.flat;
  38458. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38459. var positions = new Array();
  38460. var indices = new Array();
  38461. var normals = new Array();
  38462. var uvs = new Array();
  38463. var colors = new Array();
  38464. var index = 0;
  38465. var faceIdx = 0; // face cursor in the array "indexes"
  38466. var indexes = new Array();
  38467. var i = 0;
  38468. var f = 0;
  38469. var u, v, ang, x, y, tmp;
  38470. // default face colors and UV if undefined
  38471. if (flat) {
  38472. for (f = 0; f < nbfaces; f++) {
  38473. if (faceColors && faceColors[f] === undefined) {
  38474. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38475. }
  38476. if (faceUV && faceUV[f] === undefined) {
  38477. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38478. }
  38479. }
  38480. }
  38481. if (!flat) {
  38482. for (i = 0; i < data.vertex.length; i++) {
  38483. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38484. uvs.push(0, 0);
  38485. }
  38486. for (f = 0; f < nbfaces; f++) {
  38487. for (i = 0; i < data.face[f].length - 2; i++) {
  38488. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38489. }
  38490. }
  38491. }
  38492. else {
  38493. for (f = 0; f < nbfaces; f++) {
  38494. var fl = data.face[f].length; // number of vertices of the current face
  38495. ang = 2 * Math.PI / fl;
  38496. x = 0.5 * Math.tan(ang / 2);
  38497. y = 0.5;
  38498. // positions, uvs, colors
  38499. for (i = 0; i < fl; i++) {
  38500. // positions
  38501. 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);
  38502. indexes.push(index);
  38503. index++;
  38504. // uvs
  38505. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38506. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38507. uvs.push(u, v);
  38508. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38509. y = x * Math.sin(ang) + y * Math.cos(ang);
  38510. x = tmp;
  38511. // colors
  38512. if (faceColors) {
  38513. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38514. }
  38515. }
  38516. // indices from indexes
  38517. for (i = 0; i < fl - 2; i++) {
  38518. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38519. }
  38520. faceIdx += fl;
  38521. }
  38522. }
  38523. VertexData.ComputeNormals(positions, indices, normals);
  38524. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38525. var vertexData = new VertexData();
  38526. vertexData.positions = positions;
  38527. vertexData.indices = indices;
  38528. vertexData.normals = normals;
  38529. vertexData.uvs = uvs;
  38530. if (faceColors && flat) {
  38531. vertexData.colors = colors;
  38532. }
  38533. return vertexData;
  38534. };
  38535. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38536. /**
  38537. * Creates the VertexData for a TorusKnot
  38538. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38539. * * radius the radius of the torus knot, optional, default 2
  38540. * * tube the thickness of the tube, optional, default 0.5
  38541. * * radialSegments the number of sides on each tube segments, optional, default 32
  38542. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38543. * * p the number of windings around the z axis, optional, default 2
  38544. * * q the number of windings around the x axis, optional, default 3
  38545. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38546. * * 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)
  38547. * * 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)
  38548. * @returns the VertexData of the Torus Knot
  38549. */
  38550. VertexData.CreateTorusKnot = function (options) {
  38551. var indices = new Array();
  38552. var positions = new Array();
  38553. var normals = new Array();
  38554. var uvs = new Array();
  38555. var radius = options.radius || 2;
  38556. var tube = options.tube || 0.5;
  38557. var radialSegments = options.radialSegments || 32;
  38558. var tubularSegments = options.tubularSegments || 32;
  38559. var p = options.p || 2;
  38560. var q = options.q || 3;
  38561. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38562. // Helper
  38563. var getPos = function (angle) {
  38564. var cu = Math.cos(angle);
  38565. var su = Math.sin(angle);
  38566. var quOverP = q / p * angle;
  38567. var cs = Math.cos(quOverP);
  38568. var tx = radius * (2 + cs) * 0.5 * cu;
  38569. var ty = radius * (2 + cs) * su * 0.5;
  38570. var tz = radius * Math.sin(quOverP) * 0.5;
  38571. return new BABYLON.Vector3(tx, ty, tz);
  38572. };
  38573. // Vertices
  38574. var i;
  38575. var j;
  38576. for (i = 0; i <= radialSegments; i++) {
  38577. var modI = i % radialSegments;
  38578. var u = modI / radialSegments * 2 * p * Math.PI;
  38579. var p1 = getPos(u);
  38580. var p2 = getPos(u + 0.01);
  38581. var tang = p2.subtract(p1);
  38582. var n = p2.add(p1);
  38583. var bitan = BABYLON.Vector3.Cross(tang, n);
  38584. n = BABYLON.Vector3.Cross(bitan, tang);
  38585. bitan.normalize();
  38586. n.normalize();
  38587. for (j = 0; j < tubularSegments; j++) {
  38588. var modJ = j % tubularSegments;
  38589. var v = modJ / tubularSegments * 2 * Math.PI;
  38590. var cx = -tube * Math.cos(v);
  38591. var cy = tube * Math.sin(v);
  38592. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38593. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38594. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38595. uvs.push(i / radialSegments);
  38596. uvs.push(j / tubularSegments);
  38597. }
  38598. }
  38599. for (i = 0; i < radialSegments; i++) {
  38600. for (j = 0; j < tubularSegments; j++) {
  38601. var jNext = (j + 1) % tubularSegments;
  38602. var a = i * tubularSegments + j;
  38603. var b = (i + 1) * tubularSegments + j;
  38604. var c = (i + 1) * tubularSegments + jNext;
  38605. var d = i * tubularSegments + jNext;
  38606. indices.push(d);
  38607. indices.push(b);
  38608. indices.push(a);
  38609. indices.push(d);
  38610. indices.push(c);
  38611. indices.push(b);
  38612. }
  38613. }
  38614. // Normals
  38615. VertexData.ComputeNormals(positions, indices, normals);
  38616. // Sides
  38617. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38618. // Result
  38619. var vertexData = new VertexData();
  38620. vertexData.indices = indices;
  38621. vertexData.positions = positions;
  38622. vertexData.normals = normals;
  38623. vertexData.uvs = uvs;
  38624. return vertexData;
  38625. };
  38626. // Tools
  38627. /**
  38628. * Compute normals for given positions and indices
  38629. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38630. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38631. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38632. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38633. * * facetNormals : optional array of facet normals (vector3)
  38634. * * facetPositions : optional array of facet positions (vector3)
  38635. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38636. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38637. * * bInfo : optional bounding info, required for facetPartitioning computation
  38638. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38639. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38640. * * useRightHandedSystem: optional boolean to for right handed system computation
  38641. * * depthSort : optional boolean to enable the facet depth sort computation
  38642. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38643. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38644. */
  38645. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38646. // temporary scalar variables
  38647. var index = 0; // facet index
  38648. var p1p2x = 0.0; // p1p2 vector x coordinate
  38649. var p1p2y = 0.0; // p1p2 vector y coordinate
  38650. var p1p2z = 0.0; // p1p2 vector z coordinate
  38651. var p3p2x = 0.0; // p3p2 vector x coordinate
  38652. var p3p2y = 0.0; // p3p2 vector y coordinate
  38653. var p3p2z = 0.0; // p3p2 vector z coordinate
  38654. var faceNormalx = 0.0; // facet normal x coordinate
  38655. var faceNormaly = 0.0; // facet normal y coordinate
  38656. var faceNormalz = 0.0; // facet normal z coordinate
  38657. var length = 0.0; // facet normal length before normalization
  38658. var v1x = 0; // vector1 x index in the positions array
  38659. var v1y = 0; // vector1 y index in the positions array
  38660. var v1z = 0; // vector1 z index in the positions array
  38661. var v2x = 0; // vector2 x index in the positions array
  38662. var v2y = 0; // vector2 y index in the positions array
  38663. var v2z = 0; // vector2 z index in the positions array
  38664. var v3x = 0; // vector3 x index in the positions array
  38665. var v3y = 0; // vector3 y index in the positions array
  38666. var v3z = 0; // vector3 z index in the positions array
  38667. var computeFacetNormals = false;
  38668. var computeFacetPositions = false;
  38669. var computeFacetPartitioning = false;
  38670. var computeDepthSort = false;
  38671. var faceNormalSign = 1;
  38672. var ratio = 0;
  38673. var distanceTo = null;
  38674. if (options) {
  38675. computeFacetNormals = (options.facetNormals) ? true : false;
  38676. computeFacetPositions = (options.facetPositions) ? true : false;
  38677. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38678. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38679. ratio = options.ratio || 0;
  38680. computeDepthSort = (options.depthSort) ? true : false;
  38681. distanceTo = (options.distanceTo);
  38682. if (computeDepthSort) {
  38683. if (distanceTo === undefined) {
  38684. distanceTo = BABYLON.Vector3.Zero();
  38685. }
  38686. var depthSortedFacets = options.depthSortedFacets;
  38687. }
  38688. }
  38689. // facetPartitioning reinit if needed
  38690. var xSubRatio = 0;
  38691. var ySubRatio = 0;
  38692. var zSubRatio = 0;
  38693. var subSq = 0;
  38694. if (computeFacetPartitioning && options && options.bbSize) {
  38695. var ox = 0; // X partitioning index for facet position
  38696. var oy = 0; // Y partinioning index for facet position
  38697. var oz = 0; // Z partinioning index for facet position
  38698. var b1x = 0; // X partitioning index for facet v1 vertex
  38699. var b1y = 0; // Y partitioning index for facet v1 vertex
  38700. var b1z = 0; // z partitioning index for facet v1 vertex
  38701. var b2x = 0; // X partitioning index for facet v2 vertex
  38702. var b2y = 0; // Y partitioning index for facet v2 vertex
  38703. var b2z = 0; // Z partitioning index for facet v2 vertex
  38704. var b3x = 0; // X partitioning index for facet v3 vertex
  38705. var b3y = 0; // Y partitioning index for facet v3 vertex
  38706. var b3z = 0; // Z partitioning index for facet v3 vertex
  38707. var block_idx_o = 0; // facet barycenter block index
  38708. var block_idx_v1 = 0; // v1 vertex block index
  38709. var block_idx_v2 = 0; // v2 vertex block index
  38710. var block_idx_v3 = 0; // v3 vertex block index
  38711. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38712. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38713. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38714. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38715. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38716. subSq = options.subDiv.max * options.subDiv.max;
  38717. options.facetPartitioning.length = 0;
  38718. }
  38719. // reset the normals
  38720. for (index = 0; index < positions.length; index++) {
  38721. normals[index] = 0.0;
  38722. }
  38723. // Loop : 1 indice triplet = 1 facet
  38724. var nbFaces = (indices.length / 3) | 0;
  38725. for (index = 0; index < nbFaces; index++) {
  38726. // get the indexes of the coordinates of each vertex of the facet
  38727. v1x = indices[index * 3] * 3;
  38728. v1y = v1x + 1;
  38729. v1z = v1x + 2;
  38730. v2x = indices[index * 3 + 1] * 3;
  38731. v2y = v2x + 1;
  38732. v2z = v2x + 2;
  38733. v3x = indices[index * 3 + 2] * 3;
  38734. v3y = v3x + 1;
  38735. v3z = v3x + 2;
  38736. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38737. p1p2y = positions[v1y] - positions[v2y];
  38738. p1p2z = positions[v1z] - positions[v2z];
  38739. p3p2x = positions[v3x] - positions[v2x];
  38740. p3p2y = positions[v3y] - positions[v2y];
  38741. p3p2z = positions[v3z] - positions[v2z];
  38742. // compute the face normal with the cross product
  38743. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38744. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38745. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38746. // normalize this normal and store it in the array facetData
  38747. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38748. length = (length === 0) ? 1.0 : length;
  38749. faceNormalx /= length;
  38750. faceNormaly /= length;
  38751. faceNormalz /= length;
  38752. if (computeFacetNormals && options) {
  38753. options.facetNormals[index].x = faceNormalx;
  38754. options.facetNormals[index].y = faceNormaly;
  38755. options.facetNormals[index].z = faceNormalz;
  38756. }
  38757. if (computeFacetPositions && options) {
  38758. // compute and the facet barycenter coordinates in the array facetPositions
  38759. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38760. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38761. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38762. }
  38763. if (computeFacetPartitioning && options) {
  38764. // store the facet indexes in arrays in the main facetPartitioning array :
  38765. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38766. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38767. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38768. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38769. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38770. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38771. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38772. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38773. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38774. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38775. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38776. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38777. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38778. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38779. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38780. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38781. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38782. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38783. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38784. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38785. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38786. // push each facet index in each block containing the vertex
  38787. options.facetPartitioning[block_idx_v1].push(index);
  38788. if (block_idx_v2 != block_idx_v1) {
  38789. options.facetPartitioning[block_idx_v2].push(index);
  38790. }
  38791. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38792. options.facetPartitioning[block_idx_v3].push(index);
  38793. }
  38794. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38795. options.facetPartitioning[block_idx_o].push(index);
  38796. }
  38797. }
  38798. if (computeDepthSort && options && options.facetPositions) {
  38799. var dsf = depthSortedFacets[index];
  38800. dsf.ind = index * 3;
  38801. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38802. }
  38803. // compute the normals anyway
  38804. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38805. normals[v1y] += faceNormaly;
  38806. normals[v1z] += faceNormalz;
  38807. normals[v2x] += faceNormalx;
  38808. normals[v2y] += faceNormaly;
  38809. normals[v2z] += faceNormalz;
  38810. normals[v3x] += faceNormalx;
  38811. normals[v3y] += faceNormaly;
  38812. normals[v3z] += faceNormalz;
  38813. }
  38814. // last normalization of each normal
  38815. for (index = 0; index < normals.length / 3; index++) {
  38816. faceNormalx = normals[index * 3];
  38817. faceNormaly = normals[index * 3 + 1];
  38818. faceNormalz = normals[index * 3 + 2];
  38819. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38820. length = (length === 0) ? 1.0 : length;
  38821. faceNormalx /= length;
  38822. faceNormaly /= length;
  38823. faceNormalz /= length;
  38824. normals[index * 3] = faceNormalx;
  38825. normals[index * 3 + 1] = faceNormaly;
  38826. normals[index * 3 + 2] = faceNormalz;
  38827. }
  38828. };
  38829. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38830. var li = indices.length;
  38831. var ln = normals.length;
  38832. var i;
  38833. var n;
  38834. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38835. switch (sideOrientation) {
  38836. case BABYLON.Mesh.FRONTSIDE:
  38837. // nothing changed
  38838. break;
  38839. case BABYLON.Mesh.BACKSIDE:
  38840. var tmp;
  38841. // indices
  38842. for (i = 0; i < li; i += 3) {
  38843. tmp = indices[i];
  38844. indices[i] = indices[i + 2];
  38845. indices[i + 2] = tmp;
  38846. }
  38847. // normals
  38848. for (n = 0; n < ln; n++) {
  38849. normals[n] = -normals[n];
  38850. }
  38851. break;
  38852. case BABYLON.Mesh.DOUBLESIDE:
  38853. // positions
  38854. var lp = positions.length;
  38855. var l = lp / 3;
  38856. for (var p = 0; p < lp; p++) {
  38857. positions[lp + p] = positions[p];
  38858. }
  38859. // indices
  38860. for (i = 0; i < li; i += 3) {
  38861. indices[i + li] = indices[i + 2] + l;
  38862. indices[i + 1 + li] = indices[i + 1] + l;
  38863. indices[i + 2 + li] = indices[i] + l;
  38864. }
  38865. // normals
  38866. for (n = 0; n < ln; n++) {
  38867. normals[ln + n] = -normals[n];
  38868. }
  38869. // uvs
  38870. var lu = uvs.length;
  38871. var u = 0;
  38872. for (u = 0; u < lu; u++) {
  38873. uvs[u + lu] = uvs[u];
  38874. }
  38875. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38876. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38877. u = 0;
  38878. for (i = 0; i < lu / 2; i++) {
  38879. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38880. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38881. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38882. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38883. u += 2;
  38884. }
  38885. break;
  38886. }
  38887. };
  38888. /**
  38889. * Applies VertexData created from the imported parameters to the geometry
  38890. * @param parsedVertexData the parsed data from an imported file
  38891. * @param geometry the geometry to apply the VertexData to
  38892. */
  38893. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38894. var vertexData = new VertexData();
  38895. // positions
  38896. var positions = parsedVertexData.positions;
  38897. if (positions) {
  38898. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38899. }
  38900. // normals
  38901. var normals = parsedVertexData.normals;
  38902. if (normals) {
  38903. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38904. }
  38905. // tangents
  38906. var tangents = parsedVertexData.tangents;
  38907. if (tangents) {
  38908. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38909. }
  38910. // uvs
  38911. var uvs = parsedVertexData.uvs;
  38912. if (uvs) {
  38913. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38914. }
  38915. // uv2s
  38916. var uv2s = parsedVertexData.uv2s;
  38917. if (uv2s) {
  38918. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38919. }
  38920. // uv3s
  38921. var uv3s = parsedVertexData.uv3s;
  38922. if (uv3s) {
  38923. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38924. }
  38925. // uv4s
  38926. var uv4s = parsedVertexData.uv4s;
  38927. if (uv4s) {
  38928. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38929. }
  38930. // uv5s
  38931. var uv5s = parsedVertexData.uv5s;
  38932. if (uv5s) {
  38933. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38934. }
  38935. // uv6s
  38936. var uv6s = parsedVertexData.uv6s;
  38937. if (uv6s) {
  38938. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38939. }
  38940. // colors
  38941. var colors = parsedVertexData.colors;
  38942. if (colors) {
  38943. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38944. }
  38945. // matricesIndices
  38946. var matricesIndices = parsedVertexData.matricesIndices;
  38947. if (matricesIndices) {
  38948. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38949. }
  38950. // matricesWeights
  38951. var matricesWeights = parsedVertexData.matricesWeights;
  38952. if (matricesWeights) {
  38953. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38954. }
  38955. // indices
  38956. var indices = parsedVertexData.indices;
  38957. if (indices) {
  38958. vertexData.indices = indices;
  38959. }
  38960. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38961. };
  38962. return VertexData;
  38963. }());
  38964. BABYLON.VertexData = VertexData;
  38965. })(BABYLON || (BABYLON = {}));
  38966. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38967. var BABYLON;
  38968. (function (BABYLON) {
  38969. /**
  38970. * Class used to store geometry data (vertex buffers + index buffer)
  38971. */
  38972. var Geometry = /** @class */ (function () {
  38973. /**
  38974. * Creates a new geometry
  38975. * @param id defines the unique ID
  38976. * @param scene defines the hosting scene
  38977. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38978. * @param updatable defines if geometry must be updatable (false by default)
  38979. * @param mesh defines the mesh that will be associated with the geometry
  38980. */
  38981. function Geometry(id, scene, vertexData, updatable, mesh) {
  38982. if (updatable === void 0) { updatable = false; }
  38983. if (mesh === void 0) { mesh = null; }
  38984. /**
  38985. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38986. */
  38987. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38988. this._totalVertices = 0;
  38989. this._isDisposed = false;
  38990. this._indexBufferIsUpdatable = false;
  38991. this.id = id;
  38992. this._engine = scene.getEngine();
  38993. this._meshes = [];
  38994. this._scene = scene;
  38995. //Init vertex buffer cache
  38996. this._vertexBuffers = {};
  38997. this._indices = [];
  38998. this._updatable = updatable;
  38999. // vertexData
  39000. if (vertexData) {
  39001. this.setAllVerticesData(vertexData, updatable);
  39002. }
  39003. else {
  39004. this._totalVertices = 0;
  39005. this._indices = [];
  39006. }
  39007. if (this._engine.getCaps().vertexArrayObject) {
  39008. this._vertexArrayObjects = {};
  39009. }
  39010. // applyToMesh
  39011. if (mesh) {
  39012. if (mesh.getClassName() === "LinesMesh") {
  39013. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39014. this._updateExtend();
  39015. }
  39016. this.applyToMesh(mesh);
  39017. mesh.computeWorldMatrix(true);
  39018. }
  39019. }
  39020. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39021. /**
  39022. * 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
  39023. */
  39024. get: function () {
  39025. return this._boundingBias;
  39026. },
  39027. /**
  39028. * 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
  39029. */
  39030. set: function (value) {
  39031. if (this._boundingBias && this._boundingBias.equals(value)) {
  39032. return;
  39033. }
  39034. this._boundingBias = value.clone();
  39035. this._updateBoundingInfo(true, null);
  39036. },
  39037. enumerable: true,
  39038. configurable: true
  39039. });
  39040. /**
  39041. * Static function used to attach a new empty geometry to a mesh
  39042. * @param mesh defines the mesh to attach the geometry to
  39043. * @returns the new {BABYLON.Geometry}
  39044. */
  39045. Geometry.CreateGeometryForMesh = function (mesh) {
  39046. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39047. geometry.applyToMesh(mesh);
  39048. return geometry;
  39049. };
  39050. Object.defineProperty(Geometry.prototype, "extend", {
  39051. /**
  39052. * Gets the current extend of the geometry
  39053. */
  39054. get: function () {
  39055. return this._extend;
  39056. },
  39057. enumerable: true,
  39058. configurable: true
  39059. });
  39060. /**
  39061. * Gets the hosting scene
  39062. * @returns the hosting {BABYLON.Scene}
  39063. */
  39064. Geometry.prototype.getScene = function () {
  39065. return this._scene;
  39066. };
  39067. /**
  39068. * Gets the hosting engine
  39069. * @returns the hosting {BABYLON.Engine}
  39070. */
  39071. Geometry.prototype.getEngine = function () {
  39072. return this._engine;
  39073. };
  39074. /**
  39075. * Defines if the geometry is ready to use
  39076. * @returns true if the geometry is ready to be used
  39077. */
  39078. Geometry.prototype.isReady = function () {
  39079. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39080. };
  39081. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39082. /**
  39083. * Gets a value indicating that the geometry should not be serialized
  39084. */
  39085. get: function () {
  39086. for (var index = 0; index < this._meshes.length; index++) {
  39087. if (!this._meshes[index].doNotSerialize) {
  39088. return false;
  39089. }
  39090. }
  39091. return true;
  39092. },
  39093. enumerable: true,
  39094. configurable: true
  39095. });
  39096. /** @hidden */
  39097. Geometry.prototype._rebuild = function () {
  39098. if (this._vertexArrayObjects) {
  39099. this._vertexArrayObjects = {};
  39100. }
  39101. // Index buffer
  39102. if (this._meshes.length !== 0 && this._indices) {
  39103. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39104. }
  39105. // Vertex buffers
  39106. for (var key in this._vertexBuffers) {
  39107. var vertexBuffer = this._vertexBuffers[key];
  39108. vertexBuffer._rebuild();
  39109. }
  39110. };
  39111. /**
  39112. * Affects all gemetry data in one call
  39113. * @param vertexData defines the geometry data
  39114. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39115. */
  39116. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39117. vertexData.applyToGeometry(this, updatable);
  39118. this.notifyUpdate();
  39119. };
  39120. /**
  39121. * Set specific vertex data
  39122. * @param kind defines the data kind (Position, normal, etc...)
  39123. * @param data defines the vertex data to use
  39124. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39125. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39126. */
  39127. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39128. if (updatable === void 0) { updatable = false; }
  39129. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39130. this.setVerticesBuffer(buffer);
  39131. };
  39132. /**
  39133. * Removes a specific vertex data
  39134. * @param kind defines the data kind (Position, normal, etc...)
  39135. */
  39136. Geometry.prototype.removeVerticesData = function (kind) {
  39137. if (this._vertexBuffers[kind]) {
  39138. this._vertexBuffers[kind].dispose();
  39139. delete this._vertexBuffers[kind];
  39140. }
  39141. };
  39142. /**
  39143. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39144. * @param buffer defines the vertex buffer to use
  39145. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39146. */
  39147. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39148. if (totalVertices === void 0) { totalVertices = null; }
  39149. var kind = buffer.getKind();
  39150. if (this._vertexBuffers[kind]) {
  39151. this._vertexBuffers[kind].dispose();
  39152. }
  39153. this._vertexBuffers[kind] = buffer;
  39154. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39155. var data = buffer.getData();
  39156. if (totalVertices != null) {
  39157. this._totalVertices = totalVertices;
  39158. }
  39159. else {
  39160. if (data != null) {
  39161. this._totalVertices = data.length / (buffer.byteStride / 4);
  39162. }
  39163. }
  39164. this._updateExtend(data);
  39165. this._resetPointsArrayCache();
  39166. var meshes = this._meshes;
  39167. var numOfMeshes = meshes.length;
  39168. for (var index = 0; index < numOfMeshes; index++) {
  39169. var mesh = meshes[index];
  39170. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39171. mesh._createGlobalSubMesh(false);
  39172. mesh.computeWorldMatrix(true);
  39173. }
  39174. }
  39175. this.notifyUpdate(kind);
  39176. if (this._vertexArrayObjects) {
  39177. this._disposeVertexArrayObjects();
  39178. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39179. }
  39180. };
  39181. /**
  39182. * Update a specific vertex buffer
  39183. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39184. * It will do nothing if the buffer is not updatable
  39185. * @param kind defines the data kind (Position, normal, etc...)
  39186. * @param data defines the data to use
  39187. * @param offset defines the offset in the target buffer where to store the data
  39188. * @param useBytes set to true if the offset is in bytes
  39189. */
  39190. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39191. if (useBytes === void 0) { useBytes = false; }
  39192. var vertexBuffer = this.getVertexBuffer(kind);
  39193. if (!vertexBuffer) {
  39194. return;
  39195. }
  39196. vertexBuffer.updateDirectly(data, offset, useBytes);
  39197. this.notifyUpdate(kind);
  39198. };
  39199. /**
  39200. * Update a specific vertex buffer
  39201. * This function will create a new buffer if the current one is not updatable
  39202. * @param kind defines the data kind (Position, normal, etc...)
  39203. * @param data defines the data to use
  39204. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39205. */
  39206. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39207. if (updateExtends === void 0) { updateExtends = false; }
  39208. var vertexBuffer = this.getVertexBuffer(kind);
  39209. if (!vertexBuffer) {
  39210. return;
  39211. }
  39212. vertexBuffer.update(data);
  39213. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39214. this._updateBoundingInfo(updateExtends, data);
  39215. }
  39216. this.notifyUpdate(kind);
  39217. };
  39218. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39219. if (updateExtends) {
  39220. this._updateExtend(data);
  39221. }
  39222. var meshes = this._meshes;
  39223. var numOfMeshes = meshes.length;
  39224. this._resetPointsArrayCache();
  39225. for (var index = 0; index < numOfMeshes; index++) {
  39226. var mesh = meshes[index];
  39227. if (updateExtends) {
  39228. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39229. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39230. var subMesh = mesh.subMeshes[subIndex];
  39231. subMesh.refreshBoundingInfo();
  39232. }
  39233. }
  39234. }
  39235. };
  39236. /** @hidden */
  39237. Geometry.prototype._bind = function (effect, indexToBind) {
  39238. if (!effect) {
  39239. return;
  39240. }
  39241. if (indexToBind === undefined) {
  39242. indexToBind = this._indexBuffer;
  39243. }
  39244. var vbs = this.getVertexBuffers();
  39245. if (!vbs) {
  39246. return;
  39247. }
  39248. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39249. this._engine.bindBuffers(vbs, indexToBind, effect);
  39250. return;
  39251. }
  39252. // Using VAO
  39253. if (!this._vertexArrayObjects[effect.key]) {
  39254. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39255. }
  39256. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39257. };
  39258. /**
  39259. * Gets total number of vertices
  39260. * @returns the total number of vertices
  39261. */
  39262. Geometry.prototype.getTotalVertices = function () {
  39263. if (!this.isReady()) {
  39264. return 0;
  39265. }
  39266. return this._totalVertices;
  39267. };
  39268. /**
  39269. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39270. * @param kind defines the data kind (Position, normal, etc...)
  39271. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39272. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39273. * @returns a float array containing vertex data
  39274. */
  39275. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39276. var vertexBuffer = this.getVertexBuffer(kind);
  39277. if (!vertexBuffer) {
  39278. return null;
  39279. }
  39280. var data = vertexBuffer.getData();
  39281. if (!data) {
  39282. return null;
  39283. }
  39284. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39285. var count = this._totalVertices * vertexBuffer.getSize();
  39286. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39287. var copy_1 = new Array(count);
  39288. vertexBuffer.forEach(count, function (value, index) {
  39289. copy_1[index] = value;
  39290. });
  39291. return copy_1;
  39292. }
  39293. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39294. if (data instanceof Array) {
  39295. var offset = vertexBuffer.byteOffset / 4;
  39296. return BABYLON.Tools.Slice(data, offset, offset + count);
  39297. }
  39298. else if (data instanceof ArrayBuffer) {
  39299. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39300. }
  39301. else {
  39302. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39303. }
  39304. }
  39305. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39306. return BABYLON.Tools.Slice(data);
  39307. }
  39308. return data;
  39309. };
  39310. /**
  39311. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39312. * @param kind defines the data kind (Position, normal, etc...)
  39313. * @returns true if the vertex buffer with the specified kind is updatable
  39314. */
  39315. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39316. var vb = this._vertexBuffers[kind];
  39317. if (!vb) {
  39318. return false;
  39319. }
  39320. return vb.isUpdatable();
  39321. };
  39322. /**
  39323. * Gets a specific vertex buffer
  39324. * @param kind defines the data kind (Position, normal, etc...)
  39325. * @returns a {BABYLON.VertexBuffer}
  39326. */
  39327. Geometry.prototype.getVertexBuffer = function (kind) {
  39328. if (!this.isReady()) {
  39329. return null;
  39330. }
  39331. return this._vertexBuffers[kind];
  39332. };
  39333. /**
  39334. * Returns all vertex buffers
  39335. * @return an object holding all vertex buffers indexed by kind
  39336. */
  39337. Geometry.prototype.getVertexBuffers = function () {
  39338. if (!this.isReady()) {
  39339. return null;
  39340. }
  39341. return this._vertexBuffers;
  39342. };
  39343. /**
  39344. * Gets a boolean indicating if specific vertex buffer is present
  39345. * @param kind defines the data kind (Position, normal, etc...)
  39346. * @returns true if data is present
  39347. */
  39348. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39349. if (!this._vertexBuffers) {
  39350. if (this._delayInfo) {
  39351. return this._delayInfo.indexOf(kind) !== -1;
  39352. }
  39353. return false;
  39354. }
  39355. return this._vertexBuffers[kind] !== undefined;
  39356. };
  39357. /**
  39358. * Gets a list of all attached data kinds (Position, normal, etc...)
  39359. * @returns a list of string containing all kinds
  39360. */
  39361. Geometry.prototype.getVerticesDataKinds = function () {
  39362. var result = [];
  39363. var kind;
  39364. if (!this._vertexBuffers && this._delayInfo) {
  39365. for (kind in this._delayInfo) {
  39366. result.push(kind);
  39367. }
  39368. }
  39369. else {
  39370. for (kind in this._vertexBuffers) {
  39371. result.push(kind);
  39372. }
  39373. }
  39374. return result;
  39375. };
  39376. /**
  39377. * Update index buffer
  39378. * @param indices defines the indices to store in the index buffer
  39379. * @param offset defines the offset in the target buffer where to store the data
  39380. */
  39381. Geometry.prototype.updateIndices = function (indices, offset) {
  39382. if (!this._indexBuffer) {
  39383. return;
  39384. }
  39385. if (!this._indexBufferIsUpdatable) {
  39386. this.setIndices(indices, null, true);
  39387. }
  39388. else {
  39389. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39390. }
  39391. };
  39392. /**
  39393. * Creates a new index buffer
  39394. * @param indices defines the indices to store in the index buffer
  39395. * @param totalVertices defines the total number of vertices (could be null)
  39396. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39397. */
  39398. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39399. if (totalVertices === void 0) { totalVertices = null; }
  39400. if (updatable === void 0) { updatable = false; }
  39401. if (this._indexBuffer) {
  39402. this._engine._releaseBuffer(this._indexBuffer);
  39403. }
  39404. this._disposeVertexArrayObjects();
  39405. this._indices = indices;
  39406. this._indexBufferIsUpdatable = updatable;
  39407. if (this._meshes.length !== 0 && this._indices) {
  39408. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39409. }
  39410. if (totalVertices != undefined) { // including null and undefined
  39411. this._totalVertices = totalVertices;
  39412. }
  39413. var meshes = this._meshes;
  39414. var numOfMeshes = meshes.length;
  39415. for (var index = 0; index < numOfMeshes; index++) {
  39416. meshes[index]._createGlobalSubMesh(true);
  39417. }
  39418. this.notifyUpdate();
  39419. };
  39420. /**
  39421. * Return the total number of indices
  39422. * @returns the total number of indices
  39423. */
  39424. Geometry.prototype.getTotalIndices = function () {
  39425. if (!this.isReady()) {
  39426. return 0;
  39427. }
  39428. return this._indices.length;
  39429. };
  39430. /**
  39431. * Gets the index buffer array
  39432. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39433. * @returns the index buffer array
  39434. */
  39435. Geometry.prototype.getIndices = function (copyWhenShared) {
  39436. if (!this.isReady()) {
  39437. return null;
  39438. }
  39439. var orig = this._indices;
  39440. if (!copyWhenShared || this._meshes.length === 1) {
  39441. return orig;
  39442. }
  39443. else {
  39444. var len = orig.length;
  39445. var copy = [];
  39446. for (var i = 0; i < len; i++) {
  39447. copy.push(orig[i]);
  39448. }
  39449. return copy;
  39450. }
  39451. };
  39452. /**
  39453. * Gets the index buffer
  39454. * @return the index buffer
  39455. */
  39456. Geometry.prototype.getIndexBuffer = function () {
  39457. if (!this.isReady()) {
  39458. return null;
  39459. }
  39460. return this._indexBuffer;
  39461. };
  39462. /** @hidden */
  39463. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39464. if (effect === void 0) { effect = null; }
  39465. if (!effect || !this._vertexArrayObjects) {
  39466. return;
  39467. }
  39468. if (this._vertexArrayObjects[effect.key]) {
  39469. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39470. delete this._vertexArrayObjects[effect.key];
  39471. }
  39472. };
  39473. /**
  39474. * Release the associated resources for a specific mesh
  39475. * @param mesh defines the source mesh
  39476. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39477. */
  39478. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39479. var meshes = this._meshes;
  39480. var index = meshes.indexOf(mesh);
  39481. if (index === -1) {
  39482. return;
  39483. }
  39484. meshes.splice(index, 1);
  39485. mesh._geometry = null;
  39486. if (meshes.length === 0 && shouldDispose) {
  39487. this.dispose();
  39488. }
  39489. };
  39490. /**
  39491. * Apply current geometry to a given mesh
  39492. * @param mesh defines the mesh to apply geometry to
  39493. */
  39494. Geometry.prototype.applyToMesh = function (mesh) {
  39495. if (mesh._geometry === this) {
  39496. return;
  39497. }
  39498. var previousGeometry = mesh._geometry;
  39499. if (previousGeometry) {
  39500. previousGeometry.releaseForMesh(mesh);
  39501. }
  39502. var meshes = this._meshes;
  39503. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39504. mesh._geometry = this;
  39505. this._scene.pushGeometry(this);
  39506. meshes.push(mesh);
  39507. if (this.isReady()) {
  39508. this._applyToMesh(mesh);
  39509. }
  39510. else {
  39511. mesh._boundingInfo = this._boundingInfo;
  39512. }
  39513. };
  39514. Geometry.prototype._updateExtend = function (data) {
  39515. if (data === void 0) { data = null; }
  39516. if (!data) {
  39517. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39518. }
  39519. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39520. };
  39521. Geometry.prototype._applyToMesh = function (mesh) {
  39522. var numOfMeshes = this._meshes.length;
  39523. // vertexBuffers
  39524. for (var kind in this._vertexBuffers) {
  39525. if (numOfMeshes === 1) {
  39526. this._vertexBuffers[kind].create();
  39527. }
  39528. var buffer = this._vertexBuffers[kind].getBuffer();
  39529. if (buffer)
  39530. buffer.references = numOfMeshes;
  39531. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39532. if (!this._extend) {
  39533. this._updateExtend();
  39534. }
  39535. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39536. mesh._createGlobalSubMesh(false);
  39537. //bounding info was just created again, world matrix should be applied again.
  39538. mesh._updateBoundingInfo();
  39539. }
  39540. }
  39541. // indexBuffer
  39542. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39543. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39544. }
  39545. if (this._indexBuffer) {
  39546. this._indexBuffer.references = numOfMeshes;
  39547. }
  39548. };
  39549. Geometry.prototype.notifyUpdate = function (kind) {
  39550. if (this.onGeometryUpdated) {
  39551. this.onGeometryUpdated(this, kind);
  39552. }
  39553. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39554. var mesh = _a[_i];
  39555. mesh._markSubMeshesAsAttributesDirty();
  39556. }
  39557. };
  39558. /**
  39559. * Load the geometry if it was flagged as delay loaded
  39560. * @param scene defines the hosting scene
  39561. * @param onLoaded defines a callback called when the geometry is loaded
  39562. */
  39563. Geometry.prototype.load = function (scene, onLoaded) {
  39564. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39565. return;
  39566. }
  39567. if (this.isReady()) {
  39568. if (onLoaded) {
  39569. onLoaded();
  39570. }
  39571. return;
  39572. }
  39573. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39574. this._queueLoad(scene, onLoaded);
  39575. };
  39576. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39577. var _this = this;
  39578. if (!this.delayLoadingFile) {
  39579. return;
  39580. }
  39581. scene._addPendingData(this);
  39582. scene._loadFile(this.delayLoadingFile, function (data) {
  39583. if (!_this._delayLoadingFunction) {
  39584. return;
  39585. }
  39586. _this._delayLoadingFunction(JSON.parse(data), _this);
  39587. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39588. _this._delayInfo = [];
  39589. scene._removePendingData(_this);
  39590. var meshes = _this._meshes;
  39591. var numOfMeshes = meshes.length;
  39592. for (var index = 0; index < numOfMeshes; index++) {
  39593. _this._applyToMesh(meshes[index]);
  39594. }
  39595. if (onLoaded) {
  39596. onLoaded();
  39597. }
  39598. }, undefined, true);
  39599. };
  39600. /**
  39601. * Invert the geometry to move from a right handed system to a left handed one.
  39602. */
  39603. Geometry.prototype.toLeftHanded = function () {
  39604. // Flip faces
  39605. var tIndices = this.getIndices(false);
  39606. if (tIndices != null && tIndices.length > 0) {
  39607. for (var i = 0; i < tIndices.length; i += 3) {
  39608. var tTemp = tIndices[i + 0];
  39609. tIndices[i + 0] = tIndices[i + 2];
  39610. tIndices[i + 2] = tTemp;
  39611. }
  39612. this.setIndices(tIndices);
  39613. }
  39614. // Negate position.z
  39615. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39616. if (tPositions != null && tPositions.length > 0) {
  39617. for (var i = 0; i < tPositions.length; i += 3) {
  39618. tPositions[i + 2] = -tPositions[i + 2];
  39619. }
  39620. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39621. }
  39622. // Negate normal.z
  39623. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39624. if (tNormals != null && tNormals.length > 0) {
  39625. for (var i = 0; i < tNormals.length; i += 3) {
  39626. tNormals[i + 2] = -tNormals[i + 2];
  39627. }
  39628. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39629. }
  39630. };
  39631. // Cache
  39632. /** @hidden */
  39633. Geometry.prototype._resetPointsArrayCache = function () {
  39634. this._positions = null;
  39635. };
  39636. /** @hidden */
  39637. Geometry.prototype._generatePointsArray = function () {
  39638. if (this._positions)
  39639. return true;
  39640. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39641. if (!data || data.length === 0) {
  39642. return false;
  39643. }
  39644. this._positions = [];
  39645. for (var index = 0; index < data.length; index += 3) {
  39646. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39647. }
  39648. return true;
  39649. };
  39650. /**
  39651. * Gets a value indicating if the geometry is disposed
  39652. * @returns true if the geometry was disposed
  39653. */
  39654. Geometry.prototype.isDisposed = function () {
  39655. return this._isDisposed;
  39656. };
  39657. Geometry.prototype._disposeVertexArrayObjects = function () {
  39658. if (this._vertexArrayObjects) {
  39659. for (var kind in this._vertexArrayObjects) {
  39660. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39661. }
  39662. this._vertexArrayObjects = {};
  39663. }
  39664. };
  39665. /**
  39666. * Free all associated resources
  39667. */
  39668. Geometry.prototype.dispose = function () {
  39669. var meshes = this._meshes;
  39670. var numOfMeshes = meshes.length;
  39671. var index;
  39672. for (index = 0; index < numOfMeshes; index++) {
  39673. this.releaseForMesh(meshes[index]);
  39674. }
  39675. this._meshes = [];
  39676. this._disposeVertexArrayObjects();
  39677. for (var kind in this._vertexBuffers) {
  39678. this._vertexBuffers[kind].dispose();
  39679. }
  39680. this._vertexBuffers = {};
  39681. this._totalVertices = 0;
  39682. if (this._indexBuffer) {
  39683. this._engine._releaseBuffer(this._indexBuffer);
  39684. }
  39685. this._indexBuffer = null;
  39686. this._indices = [];
  39687. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39688. this.delayLoadingFile = null;
  39689. this._delayLoadingFunction = null;
  39690. this._delayInfo = [];
  39691. this._boundingInfo = null;
  39692. this._scene.removeGeometry(this);
  39693. this._isDisposed = true;
  39694. };
  39695. /**
  39696. * Clone the current geometry into a new geometry
  39697. * @param id defines the unique ID of the new geometry
  39698. * @returns a new geometry object
  39699. */
  39700. Geometry.prototype.copy = function (id) {
  39701. var vertexData = new BABYLON.VertexData();
  39702. vertexData.indices = [];
  39703. var indices = this.getIndices();
  39704. if (indices) {
  39705. for (var index = 0; index < indices.length; index++) {
  39706. vertexData.indices.push(indices[index]);
  39707. }
  39708. }
  39709. var updatable = false;
  39710. var stopChecking = false;
  39711. var kind;
  39712. for (kind in this._vertexBuffers) {
  39713. // using slice() to make a copy of the array and not just reference it
  39714. var data = this.getVerticesData(kind);
  39715. if (data instanceof Float32Array) {
  39716. vertexData.set(new Float32Array(data), kind);
  39717. }
  39718. else {
  39719. vertexData.set(data.slice(0), kind);
  39720. }
  39721. if (!stopChecking) {
  39722. var vb = this.getVertexBuffer(kind);
  39723. if (vb) {
  39724. updatable = vb.isUpdatable();
  39725. stopChecking = !updatable;
  39726. }
  39727. }
  39728. }
  39729. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39730. geometry.delayLoadState = this.delayLoadState;
  39731. geometry.delayLoadingFile = this.delayLoadingFile;
  39732. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39733. for (kind in this._delayInfo) {
  39734. geometry._delayInfo = geometry._delayInfo || [];
  39735. geometry._delayInfo.push(kind);
  39736. }
  39737. // Bounding info
  39738. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39739. return geometry;
  39740. };
  39741. /**
  39742. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39743. * @return a JSON representation of the current geometry data (without the vertices data)
  39744. */
  39745. Geometry.prototype.serialize = function () {
  39746. var serializationObject = {};
  39747. serializationObject.id = this.id;
  39748. serializationObject.updatable = this._updatable;
  39749. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39750. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39751. }
  39752. return serializationObject;
  39753. };
  39754. Geometry.prototype.toNumberArray = function (origin) {
  39755. if (Array.isArray(origin)) {
  39756. return origin;
  39757. }
  39758. else {
  39759. return Array.prototype.slice.call(origin);
  39760. }
  39761. };
  39762. /**
  39763. * Serialize all vertices data into a JSON oject
  39764. * @returns a JSON representation of the current geometry data
  39765. */
  39766. Geometry.prototype.serializeVerticeData = function () {
  39767. var serializationObject = this.serialize();
  39768. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39769. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39770. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39771. serializationObject.positions._updatable = true;
  39772. }
  39773. }
  39774. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39775. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39776. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39777. serializationObject.normals._updatable = true;
  39778. }
  39779. }
  39780. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39781. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39782. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39783. serializationObject.tangets._updatable = true;
  39784. }
  39785. }
  39786. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39787. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39788. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39789. serializationObject.uvs._updatable = true;
  39790. }
  39791. }
  39792. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39793. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39794. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39795. serializationObject.uv2s._updatable = true;
  39796. }
  39797. }
  39798. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39799. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39800. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39801. serializationObject.uv3s._updatable = true;
  39802. }
  39803. }
  39804. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39805. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39806. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39807. serializationObject.uv4s._updatable = true;
  39808. }
  39809. }
  39810. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39811. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39812. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39813. serializationObject.uv5s._updatable = true;
  39814. }
  39815. }
  39816. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39817. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39818. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39819. serializationObject.uv6s._updatable = true;
  39820. }
  39821. }
  39822. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39823. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39824. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39825. serializationObject.colors._updatable = true;
  39826. }
  39827. }
  39828. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39829. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39830. serializationObject.matricesIndices._isExpanded = true;
  39831. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39832. serializationObject.matricesIndices._updatable = true;
  39833. }
  39834. }
  39835. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39836. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39837. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39838. serializationObject.matricesWeights._updatable = true;
  39839. }
  39840. }
  39841. serializationObject.indices = this.toNumberArray(this.getIndices());
  39842. return serializationObject;
  39843. };
  39844. // Statics
  39845. /**
  39846. * Extracts a clone of a mesh geometry
  39847. * @param mesh defines the source mesh
  39848. * @param id defines the unique ID of the new geometry object
  39849. * @returns the new geometry object
  39850. */
  39851. Geometry.ExtractFromMesh = function (mesh, id) {
  39852. var geometry = mesh._geometry;
  39853. if (!geometry) {
  39854. return null;
  39855. }
  39856. return geometry.copy(id);
  39857. };
  39858. /**
  39859. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39860. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39861. * Be aware Math.random() could cause collisions, but:
  39862. * "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"
  39863. * @returns a string containing a new GUID
  39864. */
  39865. Geometry.RandomId = function () {
  39866. return BABYLON.Tools.RandomId();
  39867. };
  39868. /** @hidden */
  39869. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39870. var scene = mesh.getScene();
  39871. // Geometry
  39872. var geometryId = parsedGeometry.geometryId;
  39873. if (geometryId) {
  39874. var geometry = scene.getGeometryByID(geometryId);
  39875. if (geometry) {
  39876. geometry.applyToMesh(mesh);
  39877. }
  39878. }
  39879. else if (parsedGeometry instanceof ArrayBuffer) {
  39880. var binaryInfo = mesh._binaryInfo;
  39881. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39882. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39883. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39884. }
  39885. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39886. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39887. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39888. }
  39889. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39890. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39891. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39892. }
  39893. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39894. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39895. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39896. }
  39897. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39898. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39899. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39900. }
  39901. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39902. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39903. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39904. }
  39905. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39906. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39907. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39908. }
  39909. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39910. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39911. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39912. }
  39913. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39914. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39915. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39916. }
  39917. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39918. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39919. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39920. }
  39921. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39922. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39923. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39924. }
  39925. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39926. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39927. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39928. }
  39929. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39930. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39931. mesh.setIndices(indicesData, null);
  39932. }
  39933. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39934. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39935. mesh.subMeshes = [];
  39936. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39937. var materialIndex = subMeshesData[(i * 5) + 0];
  39938. var verticesStart = subMeshesData[(i * 5) + 1];
  39939. var verticesCount = subMeshesData[(i * 5) + 2];
  39940. var indexStart = subMeshesData[(i * 5) + 3];
  39941. var indexCount = subMeshesData[(i * 5) + 4];
  39942. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39943. }
  39944. }
  39945. }
  39946. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39947. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39948. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39949. if (parsedGeometry.tangents) {
  39950. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39951. }
  39952. if (parsedGeometry.uvs) {
  39953. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39954. }
  39955. if (parsedGeometry.uvs2) {
  39956. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39957. }
  39958. if (parsedGeometry.uvs3) {
  39959. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39960. }
  39961. if (parsedGeometry.uvs4) {
  39962. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39963. }
  39964. if (parsedGeometry.uvs5) {
  39965. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39966. }
  39967. if (parsedGeometry.uvs6) {
  39968. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39969. }
  39970. if (parsedGeometry.colors) {
  39971. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39972. }
  39973. if (parsedGeometry.matricesIndices) {
  39974. if (!parsedGeometry.matricesIndices._isExpanded) {
  39975. var floatIndices = [];
  39976. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39977. var matricesIndex = parsedGeometry.matricesIndices[i];
  39978. floatIndices.push(matricesIndex & 0x000000FF);
  39979. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39980. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39981. floatIndices.push(matricesIndex >> 24);
  39982. }
  39983. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39984. }
  39985. else {
  39986. delete parsedGeometry.matricesIndices._isExpanded;
  39987. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39988. }
  39989. }
  39990. if (parsedGeometry.matricesIndicesExtra) {
  39991. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39992. var floatIndices = [];
  39993. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39994. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39995. floatIndices.push(matricesIndex & 0x000000FF);
  39996. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39997. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39998. floatIndices.push(matricesIndex >> 24);
  39999. }
  40000. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40001. }
  40002. else {
  40003. delete parsedGeometry.matricesIndices._isExpanded;
  40004. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40005. }
  40006. }
  40007. if (parsedGeometry.matricesWeights) {
  40008. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40009. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40010. }
  40011. if (parsedGeometry.matricesWeightsExtra) {
  40012. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40013. }
  40014. mesh.setIndices(parsedGeometry.indices, null);
  40015. }
  40016. // SubMeshes
  40017. if (parsedGeometry.subMeshes) {
  40018. mesh.subMeshes = [];
  40019. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40020. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40021. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40022. }
  40023. }
  40024. // Flat shading
  40025. if (mesh._shouldGenerateFlatShading) {
  40026. mesh.convertToFlatShadedMesh();
  40027. delete mesh._shouldGenerateFlatShading;
  40028. }
  40029. // Update
  40030. mesh.computeWorldMatrix(true);
  40031. // Octree
  40032. var sceneOctree = scene.selectionOctree;
  40033. if (sceneOctree !== undefined && sceneOctree !== null) {
  40034. sceneOctree.addMesh(mesh);
  40035. }
  40036. };
  40037. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40038. var epsilon = 1e-3;
  40039. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40040. return;
  40041. }
  40042. var noInfluenceBoneIndex = 0.0;
  40043. if (parsedGeometry.skeletonId > -1) {
  40044. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40045. if (!skeleton) {
  40046. return;
  40047. }
  40048. noInfluenceBoneIndex = skeleton.bones.length;
  40049. }
  40050. else {
  40051. return;
  40052. }
  40053. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40054. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40055. var matricesWeights = parsedGeometry.matricesWeights;
  40056. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40057. var influencers = parsedGeometry.numBoneInfluencer;
  40058. var size = matricesWeights.length;
  40059. for (var i = 0; i < size; i += 4) {
  40060. var weight = 0.0;
  40061. var firstZeroWeight = -1;
  40062. for (var j = 0; j < 4; j++) {
  40063. var w = matricesWeights[i + j];
  40064. weight += w;
  40065. if (w < epsilon && firstZeroWeight < 0) {
  40066. firstZeroWeight = j;
  40067. }
  40068. }
  40069. if (matricesWeightsExtra) {
  40070. for (var j = 0; j < 4; j++) {
  40071. var w = matricesWeightsExtra[i + j];
  40072. weight += w;
  40073. if (w < epsilon && firstZeroWeight < 0) {
  40074. firstZeroWeight = j + 4;
  40075. }
  40076. }
  40077. }
  40078. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40079. firstZeroWeight = influencers - 1;
  40080. }
  40081. if (weight > epsilon) {
  40082. var mweight = 1.0 / weight;
  40083. for (var j = 0; j < 4; j++) {
  40084. matricesWeights[i + j] *= mweight;
  40085. }
  40086. if (matricesWeightsExtra) {
  40087. for (var j = 0; j < 4; j++) {
  40088. matricesWeightsExtra[i + j] *= mweight;
  40089. }
  40090. }
  40091. }
  40092. else {
  40093. if (firstZeroWeight >= 4) {
  40094. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40095. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40096. }
  40097. else {
  40098. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40099. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40100. }
  40101. }
  40102. }
  40103. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40104. if (parsedGeometry.matricesWeightsExtra) {
  40105. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40106. }
  40107. };
  40108. /**
  40109. * Create a new geometry from persisted data (Using .babylon file format)
  40110. * @param parsedVertexData defines the persisted data
  40111. * @param scene defines the hosting scene
  40112. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40113. * @returns the new geometry object
  40114. */
  40115. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40116. if (scene.getGeometryByID(parsedVertexData.id)) {
  40117. return null; // null since geometry could be something else than a box...
  40118. }
  40119. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40120. if (BABYLON.Tags) {
  40121. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40122. }
  40123. if (parsedVertexData.delayLoadingFile) {
  40124. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40125. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40126. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40127. geometry._delayInfo = [];
  40128. if (parsedVertexData.hasUVs) {
  40129. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40130. }
  40131. if (parsedVertexData.hasUVs2) {
  40132. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40133. }
  40134. if (parsedVertexData.hasUVs3) {
  40135. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40136. }
  40137. if (parsedVertexData.hasUVs4) {
  40138. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40139. }
  40140. if (parsedVertexData.hasUVs5) {
  40141. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40142. }
  40143. if (parsedVertexData.hasUVs6) {
  40144. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40145. }
  40146. if (parsedVertexData.hasColors) {
  40147. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40148. }
  40149. if (parsedVertexData.hasMatricesIndices) {
  40150. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40151. }
  40152. if (parsedVertexData.hasMatricesWeights) {
  40153. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40154. }
  40155. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40156. }
  40157. else {
  40158. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40159. }
  40160. scene.pushGeometry(geometry, true);
  40161. return geometry;
  40162. };
  40163. return Geometry;
  40164. }());
  40165. BABYLON.Geometry = Geometry;
  40166. // Primitives
  40167. /// Abstract class
  40168. /**
  40169. * Abstract class used to provide common services for all typed geometries
  40170. * @hidden
  40171. */
  40172. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40173. __extends(_PrimitiveGeometry, _super);
  40174. /**
  40175. * Creates a new typed geometry
  40176. * @param id defines the unique ID of the geometry
  40177. * @param scene defines the hosting scene
  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. */
  40181. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40182. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40183. if (mesh === void 0) { mesh = null; }
  40184. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40185. _this._canBeRegenerated = _canBeRegenerated;
  40186. _this._beingRegenerated = true;
  40187. _this.regenerate();
  40188. _this._beingRegenerated = false;
  40189. return _this;
  40190. }
  40191. /**
  40192. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40193. * @returns true if the geometry can be regenerated
  40194. */
  40195. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40196. return this._canBeRegenerated;
  40197. };
  40198. /**
  40199. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40200. */
  40201. _PrimitiveGeometry.prototype.regenerate = function () {
  40202. if (!this._canBeRegenerated) {
  40203. return;
  40204. }
  40205. this._beingRegenerated = true;
  40206. this.setAllVerticesData(this._regenerateVertexData(), false);
  40207. this._beingRegenerated = false;
  40208. };
  40209. /**
  40210. * Clone the geometry
  40211. * @param id defines the unique ID of the new geometry
  40212. * @returns the new geometry
  40213. */
  40214. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40215. return _super.prototype.copy.call(this, id);
  40216. };
  40217. // overrides
  40218. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40219. if (!this._beingRegenerated) {
  40220. return;
  40221. }
  40222. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40223. };
  40224. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40225. if (!this._beingRegenerated) {
  40226. return;
  40227. }
  40228. _super.prototype.setVerticesData.call(this, kind, data, false);
  40229. };
  40230. // to override
  40231. /** @hidden */
  40232. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40233. throw new Error("Abstract method");
  40234. };
  40235. _PrimitiveGeometry.prototype.copy = function (id) {
  40236. throw new Error("Must be overriden in sub-classes.");
  40237. };
  40238. _PrimitiveGeometry.prototype.serialize = function () {
  40239. var serializationObject = _super.prototype.serialize.call(this);
  40240. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40241. return serializationObject;
  40242. };
  40243. return _PrimitiveGeometry;
  40244. }(Geometry));
  40245. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40246. /**
  40247. * Creates a ribbon geometry
  40248. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40249. */
  40250. var RibbonGeometry = /** @class */ (function (_super) {
  40251. __extends(RibbonGeometry, _super);
  40252. /**
  40253. * Creates a ribbon geometry
  40254. * @param id defines the unique ID of the geometry
  40255. * @param scene defines the hosting scene
  40256. * @param pathArray defines the array of paths to use
  40257. * @param closeArray defines if the last path and the first path must be joined
  40258. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40259. * @param offset defines the offset between points
  40260. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40261. * @param mesh defines the hosting mesh (can be null)
  40262. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40263. */
  40264. function RibbonGeometry(id, scene,
  40265. /**
  40266. * Defines the array of paths to use
  40267. */
  40268. pathArray,
  40269. /**
  40270. * Defines if the last and first points of each path in your pathArray must be joined
  40271. */
  40272. closeArray,
  40273. /**
  40274. * Defines if the last and first points of each path in your pathArray must be joined
  40275. */
  40276. closePath,
  40277. /**
  40278. * Defines the offset between points
  40279. */
  40280. offset, canBeRegenerated, mesh,
  40281. /**
  40282. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40283. */
  40284. side) {
  40285. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40286. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40287. _this.pathArray = pathArray;
  40288. _this.closeArray = closeArray;
  40289. _this.closePath = closePath;
  40290. _this.offset = offset;
  40291. _this.side = side;
  40292. return _this;
  40293. }
  40294. /** @hidden */
  40295. RibbonGeometry.prototype._regenerateVertexData = function () {
  40296. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40297. };
  40298. RibbonGeometry.prototype.copy = function (id) {
  40299. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40300. };
  40301. return RibbonGeometry;
  40302. }(_PrimitiveGeometry));
  40303. BABYLON.RibbonGeometry = RibbonGeometry;
  40304. /**
  40305. * Creates a box geometry
  40306. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40307. */
  40308. var BoxGeometry = /** @class */ (function (_super) {
  40309. __extends(BoxGeometry, _super);
  40310. /**
  40311. * Creates a box geometry
  40312. * @param id defines the unique ID of the geometry
  40313. * @param scene defines the hosting scene
  40314. * @param size defines the zise of the box (width, height and depth are the same)
  40315. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40316. * @param mesh defines the hosting mesh (can be null)
  40317. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40318. */
  40319. function BoxGeometry(id, scene,
  40320. /**
  40321. * Defines the zise of the box (width, height and depth are the same)
  40322. */
  40323. size, canBeRegenerated, mesh,
  40324. /**
  40325. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40326. */
  40327. side) {
  40328. if (mesh === void 0) { mesh = null; }
  40329. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40330. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40331. _this.size = size;
  40332. _this.side = side;
  40333. return _this;
  40334. }
  40335. BoxGeometry.prototype._regenerateVertexData = function () {
  40336. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40337. };
  40338. BoxGeometry.prototype.copy = function (id) {
  40339. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40340. };
  40341. BoxGeometry.prototype.serialize = function () {
  40342. var serializationObject = _super.prototype.serialize.call(this);
  40343. serializationObject.size = this.size;
  40344. return serializationObject;
  40345. };
  40346. BoxGeometry.Parse = function (parsedBox, scene) {
  40347. if (scene.getGeometryByID(parsedBox.id)) {
  40348. return null; // null since geometry could be something else than a box...
  40349. }
  40350. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40351. if (BABYLON.Tags) {
  40352. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40353. }
  40354. scene.pushGeometry(box, true);
  40355. return box;
  40356. };
  40357. return BoxGeometry;
  40358. }(_PrimitiveGeometry));
  40359. BABYLON.BoxGeometry = BoxGeometry;
  40360. /**
  40361. * Creates a sphere geometry
  40362. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40363. */
  40364. var SphereGeometry = /** @class */ (function (_super) {
  40365. __extends(SphereGeometry, _super);
  40366. /**
  40367. * Create a new sphere geometry
  40368. * @param id defines the unique ID of the geometry
  40369. * @param scene defines the hosting scene
  40370. * @param segments defines the number of segments to use to create the sphere
  40371. * @param diameter defines the diameter of the sphere
  40372. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40373. * @param mesh defines the hosting mesh (can be null)
  40374. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40375. */
  40376. function SphereGeometry(id, scene,
  40377. /**
  40378. * Defines the number of segments to use to create the sphere
  40379. */
  40380. segments,
  40381. /**
  40382. * Defines the diameter of the sphere
  40383. */
  40384. diameter, canBeRegenerated, mesh,
  40385. /**
  40386. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40387. */
  40388. side) {
  40389. if (mesh === void 0) { mesh = null; }
  40390. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40391. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40392. _this.segments = segments;
  40393. _this.diameter = diameter;
  40394. _this.side = side;
  40395. return _this;
  40396. }
  40397. SphereGeometry.prototype._regenerateVertexData = function () {
  40398. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40399. };
  40400. SphereGeometry.prototype.copy = function (id) {
  40401. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40402. };
  40403. SphereGeometry.prototype.serialize = function () {
  40404. var serializationObject = _super.prototype.serialize.call(this);
  40405. serializationObject.segments = this.segments;
  40406. serializationObject.diameter = this.diameter;
  40407. return serializationObject;
  40408. };
  40409. SphereGeometry.Parse = function (parsedSphere, scene) {
  40410. if (scene.getGeometryByID(parsedSphere.id)) {
  40411. return null; // null since geometry could be something else than a sphere...
  40412. }
  40413. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40414. if (BABYLON.Tags) {
  40415. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40416. }
  40417. scene.pushGeometry(sphere, true);
  40418. return sphere;
  40419. };
  40420. return SphereGeometry;
  40421. }(_PrimitiveGeometry));
  40422. BABYLON.SphereGeometry = SphereGeometry;
  40423. /**
  40424. * Creates a disc geometry
  40425. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40426. */
  40427. var DiscGeometry = /** @class */ (function (_super) {
  40428. __extends(DiscGeometry, _super);
  40429. /**
  40430. * Creates a new disc geometry
  40431. * @param id defines the unique ID of the geometry
  40432. * @param scene defines the hosting scene
  40433. * @param radius defines the radius of the disc
  40434. * @param tessellation defines the tesselation factor to apply to the disc
  40435. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40436. * @param mesh defines the hosting mesh (can be null)
  40437. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40438. */
  40439. function DiscGeometry(id, scene,
  40440. /**
  40441. * Defines the radius of the disc
  40442. */
  40443. radius,
  40444. /**
  40445. * Defines the tesselation factor to apply to the disc
  40446. */
  40447. tessellation, canBeRegenerated, mesh,
  40448. /**
  40449. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40450. */
  40451. side) {
  40452. if (mesh === void 0) { mesh = null; }
  40453. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40454. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40455. _this.radius = radius;
  40456. _this.tessellation = tessellation;
  40457. _this.side = side;
  40458. return _this;
  40459. }
  40460. DiscGeometry.prototype._regenerateVertexData = function () {
  40461. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40462. };
  40463. DiscGeometry.prototype.copy = function (id) {
  40464. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40465. };
  40466. return DiscGeometry;
  40467. }(_PrimitiveGeometry));
  40468. BABYLON.DiscGeometry = DiscGeometry;
  40469. /**
  40470. * Creates a new cylinder geometry
  40471. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40472. */
  40473. var CylinderGeometry = /** @class */ (function (_super) {
  40474. __extends(CylinderGeometry, _super);
  40475. /**
  40476. * Creates a new cylinder geometry
  40477. * @param id defines the unique ID of the geometry
  40478. * @param scene defines the hosting scene
  40479. * @param height defines the height of the cylinder
  40480. * @param diameterTop defines the diameter of the cylinder's top cap
  40481. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40482. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40483. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40484. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40485. * @param mesh defines the hosting mesh (can be null)
  40486. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40487. */
  40488. function CylinderGeometry(id, scene,
  40489. /**
  40490. * Defines the height of the cylinder
  40491. */
  40492. height,
  40493. /**
  40494. * Defines the diameter of the cylinder's top cap
  40495. */
  40496. diameterTop,
  40497. /**
  40498. * Defines the diameter of the cylinder's bottom cap
  40499. */
  40500. diameterBottom,
  40501. /**
  40502. * Defines the tessellation factor to apply to the cylinder
  40503. */
  40504. tessellation,
  40505. /**
  40506. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40507. */
  40508. subdivisions, canBeRegenerated, mesh,
  40509. /**
  40510. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40511. */
  40512. side) {
  40513. if (subdivisions === void 0) { subdivisions = 1; }
  40514. if (mesh === void 0) { mesh = null; }
  40515. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40516. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40517. _this.height = height;
  40518. _this.diameterTop = diameterTop;
  40519. _this.diameterBottom = diameterBottom;
  40520. _this.tessellation = tessellation;
  40521. _this.subdivisions = subdivisions;
  40522. _this.side = side;
  40523. return _this;
  40524. }
  40525. CylinderGeometry.prototype._regenerateVertexData = function () {
  40526. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40527. };
  40528. CylinderGeometry.prototype.copy = function (id) {
  40529. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40530. };
  40531. CylinderGeometry.prototype.serialize = function () {
  40532. var serializationObject = _super.prototype.serialize.call(this);
  40533. serializationObject.height = this.height;
  40534. serializationObject.diameterTop = this.diameterTop;
  40535. serializationObject.diameterBottom = this.diameterBottom;
  40536. serializationObject.tessellation = this.tessellation;
  40537. return serializationObject;
  40538. };
  40539. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40540. if (scene.getGeometryByID(parsedCylinder.id)) {
  40541. return null; // null since geometry could be something else than a cylinder...
  40542. }
  40543. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40544. if (BABYLON.Tags) {
  40545. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40546. }
  40547. scene.pushGeometry(cylinder, true);
  40548. return cylinder;
  40549. };
  40550. return CylinderGeometry;
  40551. }(_PrimitiveGeometry));
  40552. BABYLON.CylinderGeometry = CylinderGeometry;
  40553. /**
  40554. * Creates a new torus geometry
  40555. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40556. */
  40557. var TorusGeometry = /** @class */ (function (_super) {
  40558. __extends(TorusGeometry, _super);
  40559. /**
  40560. * Creates a new torus geometry
  40561. * @param id defines the unique ID of the geometry
  40562. * @param scene defines the hosting scene
  40563. * @param diameter defines the diameter of the torus
  40564. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40565. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40566. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40567. * @param mesh defines the hosting mesh (can be null)
  40568. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40569. */
  40570. function TorusGeometry(id, scene,
  40571. /**
  40572. * Defines the diameter of the torus
  40573. */
  40574. diameter,
  40575. /**
  40576. * Defines the thickness of the torus (ie. internal diameter)
  40577. */
  40578. thickness,
  40579. /**
  40580. * Defines the tesselation factor to apply to the torus
  40581. */
  40582. tessellation, canBeRegenerated, mesh,
  40583. /**
  40584. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40585. */
  40586. side) {
  40587. if (mesh === void 0) { mesh = null; }
  40588. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40589. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40590. _this.diameter = diameter;
  40591. _this.thickness = thickness;
  40592. _this.tessellation = tessellation;
  40593. _this.side = side;
  40594. return _this;
  40595. }
  40596. TorusGeometry.prototype._regenerateVertexData = function () {
  40597. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40598. };
  40599. TorusGeometry.prototype.copy = function (id) {
  40600. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40601. };
  40602. TorusGeometry.prototype.serialize = function () {
  40603. var serializationObject = _super.prototype.serialize.call(this);
  40604. serializationObject.diameter = this.diameter;
  40605. serializationObject.thickness = this.thickness;
  40606. serializationObject.tessellation = this.tessellation;
  40607. return serializationObject;
  40608. };
  40609. TorusGeometry.Parse = function (parsedTorus, scene) {
  40610. if (scene.getGeometryByID(parsedTorus.id)) {
  40611. return null; // null since geometry could be something else than a torus...
  40612. }
  40613. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40614. if (BABYLON.Tags) {
  40615. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40616. }
  40617. scene.pushGeometry(torus, true);
  40618. return torus;
  40619. };
  40620. return TorusGeometry;
  40621. }(_PrimitiveGeometry));
  40622. BABYLON.TorusGeometry = TorusGeometry;
  40623. /**
  40624. * Creates a new ground geometry
  40625. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40626. */
  40627. var GroundGeometry = /** @class */ (function (_super) {
  40628. __extends(GroundGeometry, _super);
  40629. /**
  40630. * Creates a new ground geometry
  40631. * @param id defines the unique ID of the geometry
  40632. * @param scene defines the hosting scene
  40633. * @param width defines the width of the ground
  40634. * @param height defines the height of the ground
  40635. * @param subdivisions defines the subdivisions to apply to the ground
  40636. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40637. * @param mesh defines the hosting mesh (can be null)
  40638. */
  40639. function GroundGeometry(id, scene,
  40640. /**
  40641. * Defines the width of the ground
  40642. */
  40643. width,
  40644. /**
  40645. * Defines the height of the ground
  40646. */
  40647. height,
  40648. /**
  40649. * Defines the subdivisions to apply to the ground
  40650. */
  40651. subdivisions, canBeRegenerated, mesh) {
  40652. if (mesh === void 0) { mesh = null; }
  40653. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40654. _this.width = width;
  40655. _this.height = height;
  40656. _this.subdivisions = subdivisions;
  40657. return _this;
  40658. }
  40659. GroundGeometry.prototype._regenerateVertexData = function () {
  40660. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40661. };
  40662. GroundGeometry.prototype.copy = function (id) {
  40663. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40664. };
  40665. GroundGeometry.prototype.serialize = function () {
  40666. var serializationObject = _super.prototype.serialize.call(this);
  40667. serializationObject.width = this.width;
  40668. serializationObject.height = this.height;
  40669. serializationObject.subdivisions = this.subdivisions;
  40670. return serializationObject;
  40671. };
  40672. GroundGeometry.Parse = function (parsedGround, scene) {
  40673. if (scene.getGeometryByID(parsedGround.id)) {
  40674. return null; // null since geometry could be something else than a ground...
  40675. }
  40676. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40677. if (BABYLON.Tags) {
  40678. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40679. }
  40680. scene.pushGeometry(ground, true);
  40681. return ground;
  40682. };
  40683. return GroundGeometry;
  40684. }(_PrimitiveGeometry));
  40685. BABYLON.GroundGeometry = GroundGeometry;
  40686. /**
  40687. * Creates a tiled ground geometry
  40688. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40689. */
  40690. var TiledGroundGeometry = /** @class */ (function (_super) {
  40691. __extends(TiledGroundGeometry, _super);
  40692. /**
  40693. * Creates a tiled ground geometry
  40694. * @param id defines the unique ID of the geometry
  40695. * @param scene defines the hosting scene
  40696. * @param xmin defines the minimum value on X axis
  40697. * @param zmin defines the minimum value on Z axis
  40698. * @param xmax defines the maximum value on X axis
  40699. * @param zmax defines the maximum value on Z axis
  40700. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40701. * @param precision defines the precision to use when computing the tiles
  40702. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40703. * @param mesh defines the hosting mesh (can be null)
  40704. */
  40705. function TiledGroundGeometry(id, scene,
  40706. /**
  40707. * Defines the minimum value on X axis
  40708. */
  40709. xmin,
  40710. /**
  40711. * Defines the minimum value on Z axis
  40712. */
  40713. zmin,
  40714. /**
  40715. * Defines the maximum value on X axis
  40716. */
  40717. xmax,
  40718. /**
  40719. * Defines the maximum value on Z axis
  40720. */
  40721. zmax,
  40722. /**
  40723. * Defines the subdivisions to apply to the ground
  40724. */
  40725. subdivisions,
  40726. /**
  40727. * Defines the precision to use when computing the tiles
  40728. */
  40729. precision, canBeRegenerated, mesh) {
  40730. if (mesh === void 0) { mesh = null; }
  40731. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40732. _this.xmin = xmin;
  40733. _this.zmin = zmin;
  40734. _this.xmax = xmax;
  40735. _this.zmax = zmax;
  40736. _this.subdivisions = subdivisions;
  40737. _this.precision = precision;
  40738. return _this;
  40739. }
  40740. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40741. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40742. };
  40743. TiledGroundGeometry.prototype.copy = function (id) {
  40744. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40745. };
  40746. return TiledGroundGeometry;
  40747. }(_PrimitiveGeometry));
  40748. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40749. /**
  40750. * Creates a plane geometry
  40751. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40752. */
  40753. var PlaneGeometry = /** @class */ (function (_super) {
  40754. __extends(PlaneGeometry, _super);
  40755. /**
  40756. * Creates a plane geometry
  40757. * @param id defines the unique ID of the geometry
  40758. * @param scene defines the hosting scene
  40759. * @param size defines the size of the plane (width === height)
  40760. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40761. * @param mesh defines the hosting mesh (can be null)
  40762. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40763. */
  40764. function PlaneGeometry(id, scene,
  40765. /**
  40766. * Defines the size of the plane (width === height)
  40767. */
  40768. size, canBeRegenerated, mesh,
  40769. /**
  40770. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40771. */
  40772. side) {
  40773. if (mesh === void 0) { mesh = null; }
  40774. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40775. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40776. _this.size = size;
  40777. _this.side = side;
  40778. return _this;
  40779. }
  40780. PlaneGeometry.prototype._regenerateVertexData = function () {
  40781. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40782. };
  40783. PlaneGeometry.prototype.copy = function (id) {
  40784. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40785. };
  40786. PlaneGeometry.prototype.serialize = function () {
  40787. var serializationObject = _super.prototype.serialize.call(this);
  40788. serializationObject.size = this.size;
  40789. return serializationObject;
  40790. };
  40791. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40792. if (scene.getGeometryByID(parsedPlane.id)) {
  40793. return null; // null since geometry could be something else than a ground...
  40794. }
  40795. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40796. if (BABYLON.Tags) {
  40797. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40798. }
  40799. scene.pushGeometry(plane, true);
  40800. return plane;
  40801. };
  40802. return PlaneGeometry;
  40803. }(_PrimitiveGeometry));
  40804. BABYLON.PlaneGeometry = PlaneGeometry;
  40805. /**
  40806. * Creates a torus knot geometry
  40807. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40808. */
  40809. var TorusKnotGeometry = /** @class */ (function (_super) {
  40810. __extends(TorusKnotGeometry, _super);
  40811. /**
  40812. * Creates a torus knot geometry
  40813. * @param id defines the unique ID of the geometry
  40814. * @param scene defines the hosting scene
  40815. * @param radius defines the radius of the torus knot
  40816. * @param tube defines the thickness of the torus knot tube
  40817. * @param radialSegments defines the number of radial segments
  40818. * @param tubularSegments defines the number of tubular segments
  40819. * @param p defines the first number of windings
  40820. * @param q defines the second number of windings
  40821. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40822. * @param mesh defines the hosting mesh (can be null)
  40823. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40824. */
  40825. function TorusKnotGeometry(id, scene,
  40826. /**
  40827. * Defines the radius of the torus knot
  40828. */
  40829. radius,
  40830. /**
  40831. * Defines the thickness of the torus knot tube
  40832. */
  40833. tube,
  40834. /**
  40835. * Defines the number of radial segments
  40836. */
  40837. radialSegments,
  40838. /**
  40839. * Defines the number of tubular segments
  40840. */
  40841. tubularSegments,
  40842. /**
  40843. * Defines the first number of windings
  40844. */
  40845. p,
  40846. /**
  40847. * Defines the second number of windings
  40848. */
  40849. q, canBeRegenerated, mesh,
  40850. /**
  40851. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40852. */
  40853. side) {
  40854. if (mesh === void 0) { mesh = null; }
  40855. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40856. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40857. _this.radius = radius;
  40858. _this.tube = tube;
  40859. _this.radialSegments = radialSegments;
  40860. _this.tubularSegments = tubularSegments;
  40861. _this.p = p;
  40862. _this.q = q;
  40863. _this.side = side;
  40864. return _this;
  40865. }
  40866. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40867. 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 });
  40868. };
  40869. TorusKnotGeometry.prototype.copy = function (id) {
  40870. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40871. };
  40872. TorusKnotGeometry.prototype.serialize = function () {
  40873. var serializationObject = _super.prototype.serialize.call(this);
  40874. serializationObject.radius = this.radius;
  40875. serializationObject.tube = this.tube;
  40876. serializationObject.radialSegments = this.radialSegments;
  40877. serializationObject.tubularSegments = this.tubularSegments;
  40878. serializationObject.p = this.p;
  40879. serializationObject.q = this.q;
  40880. return serializationObject;
  40881. };
  40882. ;
  40883. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40884. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40885. return null; // null since geometry could be something else than a ground...
  40886. }
  40887. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40888. if (BABYLON.Tags) {
  40889. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40890. }
  40891. scene.pushGeometry(torusKnot, true);
  40892. return torusKnot;
  40893. };
  40894. return TorusKnotGeometry;
  40895. }(_PrimitiveGeometry));
  40896. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40897. //}
  40898. })(BABYLON || (BABYLON = {}));
  40899. //# sourceMappingURL=babylon.geometry.js.map
  40900. var BABYLON;
  40901. (function (BABYLON) {
  40902. /**
  40903. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40904. */
  40905. var PerformanceMonitor = /** @class */ (function () {
  40906. /**
  40907. * constructor
  40908. * @param frameSampleSize The number of samples required to saturate the sliding window
  40909. */
  40910. function PerformanceMonitor(frameSampleSize) {
  40911. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40912. this._enabled = true;
  40913. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40914. }
  40915. /**
  40916. * Samples current frame
  40917. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40918. */
  40919. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40920. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40921. if (!this._enabled)
  40922. return;
  40923. if (this._lastFrameTimeMs != null) {
  40924. var dt = timeMs - this._lastFrameTimeMs;
  40925. this._rollingFrameTime.add(dt);
  40926. }
  40927. this._lastFrameTimeMs = timeMs;
  40928. };
  40929. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40930. /**
  40931. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40932. * @return Average frame time in milliseconds
  40933. */
  40934. get: function () {
  40935. return this._rollingFrameTime.average;
  40936. },
  40937. enumerable: true,
  40938. configurable: true
  40939. });
  40940. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40941. /**
  40942. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40943. * @return Frame time variance in milliseconds squared
  40944. */
  40945. get: function () {
  40946. return this._rollingFrameTime.variance;
  40947. },
  40948. enumerable: true,
  40949. configurable: true
  40950. });
  40951. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40952. /**
  40953. * Returns the frame time of the most recent frame
  40954. * @return Frame time in milliseconds
  40955. */
  40956. get: function () {
  40957. return this._rollingFrameTime.history(0);
  40958. },
  40959. enumerable: true,
  40960. configurable: true
  40961. });
  40962. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40963. /**
  40964. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40965. * @return Framerate in frames per second
  40966. */
  40967. get: function () {
  40968. return 1000.0 / this._rollingFrameTime.average;
  40969. },
  40970. enumerable: true,
  40971. configurable: true
  40972. });
  40973. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40974. /**
  40975. * Returns the average framerate in frames per second using the most recent frame time
  40976. * @return Framerate in frames per second
  40977. */
  40978. get: function () {
  40979. var history = this._rollingFrameTime.history(0);
  40980. if (history === 0) {
  40981. return 0;
  40982. }
  40983. return 1000.0 / history;
  40984. },
  40985. enumerable: true,
  40986. configurable: true
  40987. });
  40988. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40989. /**
  40990. * Returns true if enough samples have been taken to completely fill the sliding window
  40991. * @return true if saturated
  40992. */
  40993. get: function () {
  40994. return this._rollingFrameTime.isSaturated();
  40995. },
  40996. enumerable: true,
  40997. configurable: true
  40998. });
  40999. /**
  41000. * Enables contributions to the sliding window sample set
  41001. */
  41002. PerformanceMonitor.prototype.enable = function () {
  41003. this._enabled = true;
  41004. };
  41005. /**
  41006. * Disables contributions to the sliding window sample set
  41007. * Samples will not be interpolated over the disabled period
  41008. */
  41009. PerformanceMonitor.prototype.disable = function () {
  41010. this._enabled = false;
  41011. //clear last sample to avoid interpolating over the disabled period when next enabled
  41012. this._lastFrameTimeMs = null;
  41013. };
  41014. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41015. /**
  41016. * Returns true if sampling is enabled
  41017. * @return true if enabled
  41018. */
  41019. get: function () {
  41020. return this._enabled;
  41021. },
  41022. enumerable: true,
  41023. configurable: true
  41024. });
  41025. /**
  41026. * Resets performance monitor
  41027. */
  41028. PerformanceMonitor.prototype.reset = function () {
  41029. //clear last sample to avoid interpolating over the disabled period when next enabled
  41030. this._lastFrameTimeMs = null;
  41031. //wipe record
  41032. this._rollingFrameTime.reset();
  41033. };
  41034. return PerformanceMonitor;
  41035. }());
  41036. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41037. /**
  41038. * RollingAverage
  41039. *
  41040. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41041. */
  41042. var RollingAverage = /** @class */ (function () {
  41043. /**
  41044. * constructor
  41045. * @param length The number of samples required to saturate the sliding window
  41046. */
  41047. function RollingAverage(length) {
  41048. this._samples = new Array(length);
  41049. this.reset();
  41050. }
  41051. /**
  41052. * Adds a sample to the sample set
  41053. * @param v The sample value
  41054. */
  41055. RollingAverage.prototype.add = function (v) {
  41056. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41057. var delta;
  41058. //we need to check if we've already wrapped round
  41059. if (this.isSaturated()) {
  41060. //remove bottom of stack from mean
  41061. var bottomValue = this._samples[this._pos];
  41062. delta = bottomValue - this.average;
  41063. this.average -= delta / (this._sampleCount - 1);
  41064. this._m2 -= delta * (bottomValue - this.average);
  41065. }
  41066. else {
  41067. this._sampleCount++;
  41068. }
  41069. //add new value to mean
  41070. delta = v - this.average;
  41071. this.average += delta / (this._sampleCount);
  41072. this._m2 += delta * (v - this.average);
  41073. //set the new variance
  41074. this.variance = this._m2 / (this._sampleCount - 1);
  41075. this._samples[this._pos] = v;
  41076. this._pos++;
  41077. this._pos %= this._samples.length; //positive wrap around
  41078. };
  41079. /**
  41080. * Returns previously added values or null if outside of history or outside the sliding window domain
  41081. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41082. * @return Value previously recorded with add() or null if outside of range
  41083. */
  41084. RollingAverage.prototype.history = function (i) {
  41085. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41086. return 0;
  41087. }
  41088. var i0 = this._wrapPosition(this._pos - 1.0);
  41089. return this._samples[this._wrapPosition(i0 - i)];
  41090. };
  41091. /**
  41092. * Returns true if enough samples have been taken to completely fill the sliding window
  41093. * @return true if sample-set saturated
  41094. */
  41095. RollingAverage.prototype.isSaturated = function () {
  41096. return this._sampleCount >= this._samples.length;
  41097. };
  41098. /**
  41099. * Resets the rolling average (equivalent to 0 samples taken so far)
  41100. */
  41101. RollingAverage.prototype.reset = function () {
  41102. this.average = 0;
  41103. this.variance = 0;
  41104. this._sampleCount = 0;
  41105. this._pos = 0;
  41106. this._m2 = 0;
  41107. };
  41108. /**
  41109. * Wraps a value around the sample range boundaries
  41110. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41111. * @return Wrapped position in sample range
  41112. */
  41113. RollingAverage.prototype._wrapPosition = function (i) {
  41114. var max = this._samples.length;
  41115. return ((i % max) + max) % max;
  41116. };
  41117. return RollingAverage;
  41118. }());
  41119. BABYLON.RollingAverage = RollingAverage;
  41120. })(BABYLON || (BABYLON = {}));
  41121. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41122. var BABYLON;
  41123. (function (BABYLON) {
  41124. /**
  41125. * "Static Class" containing the most commonly used helper while dealing with material for
  41126. * rendering purpose.
  41127. *
  41128. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41129. *
  41130. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41131. */
  41132. var MaterialHelper = /** @class */ (function () {
  41133. function MaterialHelper() {
  41134. }
  41135. /**
  41136. * Bind the current view position to an effect.
  41137. * @param effect The effect to be bound
  41138. * @param scene The scene the eyes position is used from
  41139. */
  41140. MaterialHelper.BindEyePosition = function (effect, scene) {
  41141. if (scene._forcedViewPosition) {
  41142. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41143. return;
  41144. }
  41145. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41146. };
  41147. /**
  41148. * Helps preparing the defines values about the UVs in used in the effect.
  41149. * UVs are shared as much as we can accross chanels in the shaders.
  41150. * @param texture The texture we are preparing the UVs for
  41151. * @param defines The defines to update
  41152. * @param key The chanel key "diffuse", "specular"... used in the shader
  41153. */
  41154. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41155. defines._needUVs = true;
  41156. defines[key] = true;
  41157. if (texture.getTextureMatrix().isIdentity(true)) {
  41158. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41159. if (texture.coordinatesIndex === 0) {
  41160. defines["MAINUV1"] = true;
  41161. }
  41162. else {
  41163. defines["MAINUV2"] = true;
  41164. }
  41165. }
  41166. else {
  41167. defines[key + "DIRECTUV"] = 0;
  41168. }
  41169. };
  41170. /**
  41171. * Binds a texture matrix value to its corrsponding uniform
  41172. * @param texture The texture to bind the matrix for
  41173. * @param uniformBuffer The uniform buffer receivin the data
  41174. * @param key The chanel key "diffuse", "specular"... used in the shader
  41175. */
  41176. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41177. var matrix = texture.getTextureMatrix();
  41178. if (!matrix.isIdentity(true)) {
  41179. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41180. }
  41181. };
  41182. /**
  41183. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41184. * @param mesh defines the current mesh
  41185. * @param scene defines the current scene
  41186. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41187. * @param pointsCloud defines if point cloud rendering has to be turned on
  41188. * @param fogEnabled defines if fog has to be turned on
  41189. * @param alphaTest defines if alpha testing has to be turned on
  41190. * @param defines defines the current list of defines
  41191. */
  41192. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41193. if (defines._areMiscDirty) {
  41194. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41195. defines["POINTSIZE"] = pointsCloud;
  41196. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41197. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41198. defines["ALPHATEST"] = alphaTest;
  41199. }
  41200. };
  41201. /**
  41202. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41203. * @param scene defines the current scene
  41204. * @param engine defines the current engine
  41205. * @param defines specifies the list of active defines
  41206. * @param useInstances defines if instances have to be turned on
  41207. * @param useClipPlane defines if clip plane have to be turned on
  41208. */
  41209. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41210. if (useClipPlane === void 0) { useClipPlane = null; }
  41211. var changed = false;
  41212. if (useClipPlane == null) {
  41213. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41214. }
  41215. if (defines["CLIPPLANE"] !== useClipPlane) {
  41216. defines["CLIPPLANE"] = useClipPlane;
  41217. changed = true;
  41218. }
  41219. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41220. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41221. changed = true;
  41222. }
  41223. if (defines["INSTANCES"] !== useInstances) {
  41224. defines["INSTANCES"] = useInstances;
  41225. changed = true;
  41226. }
  41227. if (changed) {
  41228. defines.markAsUnprocessed();
  41229. }
  41230. };
  41231. /**
  41232. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41233. * @param mesh The mesh containing the geometry data we will draw
  41234. * @param defines The defines to update
  41235. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41236. * @param useBones Precise whether bones should be used or not (override mesh info)
  41237. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41238. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41239. * @returns false if defines are considered not dirty and have not been checked
  41240. */
  41241. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41242. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41243. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41244. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41245. return false;
  41246. }
  41247. defines._normals = defines._needNormals;
  41248. defines._uvs = defines._needUVs;
  41249. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41250. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41251. defines["TANGENT"] = true;
  41252. }
  41253. if (defines._needUVs) {
  41254. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41255. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41256. }
  41257. else {
  41258. defines["UV1"] = false;
  41259. defines["UV2"] = false;
  41260. }
  41261. if (useVertexColor) {
  41262. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41263. defines["VERTEXCOLOR"] = hasVertexColors;
  41264. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41265. }
  41266. if (useBones) {
  41267. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41268. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41269. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41270. }
  41271. else {
  41272. defines["NUM_BONE_INFLUENCERS"] = 0;
  41273. defines["BonesPerMesh"] = 0;
  41274. }
  41275. }
  41276. if (useMorphTargets) {
  41277. var manager = mesh.morphTargetManager;
  41278. if (manager) {
  41279. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41280. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41281. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41282. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41283. }
  41284. else {
  41285. defines["MORPHTARGETS_TANGENT"] = false;
  41286. defines["MORPHTARGETS_NORMAL"] = false;
  41287. defines["MORPHTARGETS"] = false;
  41288. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41289. }
  41290. }
  41291. return true;
  41292. };
  41293. /**
  41294. * Prepares the defines related to the light information passed in parameter
  41295. * @param scene The scene we are intending to draw
  41296. * @param mesh The mesh the effect is compiling for
  41297. * @param defines The defines to update
  41298. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41299. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41300. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41301. * @returns true if normals will be required for the rest of the effect
  41302. */
  41303. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41304. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41305. if (disableLighting === void 0) { disableLighting = false; }
  41306. if (!defines._areLightsDirty) {
  41307. return defines._needNormals;
  41308. }
  41309. var lightIndex = 0;
  41310. var needNormals = false;
  41311. var needRebuild = false;
  41312. var lightmapMode = false;
  41313. var shadowEnabled = false;
  41314. var specularEnabled = false;
  41315. if (scene.lightsEnabled && !disableLighting) {
  41316. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41317. var light = _a[_i];
  41318. needNormals = true;
  41319. if (defines["LIGHT" + lightIndex] === undefined) {
  41320. needRebuild = true;
  41321. }
  41322. defines["LIGHT" + lightIndex] = true;
  41323. defines["SPOTLIGHT" + lightIndex] = false;
  41324. defines["HEMILIGHT" + lightIndex] = false;
  41325. defines["POINTLIGHT" + lightIndex] = false;
  41326. defines["DIRLIGHT" + lightIndex] = false;
  41327. var type;
  41328. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41329. type = "SPOTLIGHT" + lightIndex;
  41330. var spotLight = light;
  41331. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41332. }
  41333. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41334. type = "HEMILIGHT" + lightIndex;
  41335. }
  41336. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41337. type = "POINTLIGHT" + lightIndex;
  41338. }
  41339. else {
  41340. type = "DIRLIGHT" + lightIndex;
  41341. }
  41342. defines[type] = true;
  41343. // Specular
  41344. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41345. specularEnabled = true;
  41346. }
  41347. // Shadows
  41348. defines["SHADOW" + lightIndex] = false;
  41349. defines["SHADOWPCF" + lightIndex] = false;
  41350. defines["SHADOWPCSS" + lightIndex] = false;
  41351. defines["SHADOWPOISSON" + lightIndex] = false;
  41352. defines["SHADOWESM" + lightIndex] = false;
  41353. defines["SHADOWCUBE" + lightIndex] = false;
  41354. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41355. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41356. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41357. var shadowGenerator = light.getShadowGenerator();
  41358. if (shadowGenerator) {
  41359. shadowEnabled = true;
  41360. shadowGenerator.prepareDefines(defines, lightIndex);
  41361. }
  41362. }
  41363. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41364. lightmapMode = true;
  41365. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41366. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41367. }
  41368. else {
  41369. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41370. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41371. }
  41372. lightIndex++;
  41373. if (lightIndex === maxSimultaneousLights)
  41374. break;
  41375. }
  41376. }
  41377. defines["SPECULARTERM"] = specularEnabled;
  41378. defines["SHADOWS"] = shadowEnabled;
  41379. // Resetting all other lights if any
  41380. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41381. if (defines["LIGHT" + index] !== undefined) {
  41382. defines["LIGHT" + index] = false;
  41383. defines["HEMILIGHT" + lightIndex] = false;
  41384. defines["POINTLIGHT" + lightIndex] = false;
  41385. defines["DIRLIGHT" + lightIndex] = false;
  41386. defines["SPOTLIGHT" + lightIndex] = false;
  41387. defines["SHADOW" + lightIndex] = false;
  41388. }
  41389. }
  41390. var caps = scene.getEngine().getCaps();
  41391. if (defines["SHADOWFLOAT"] === undefined) {
  41392. needRebuild = true;
  41393. }
  41394. defines["SHADOWFLOAT"] = shadowEnabled &&
  41395. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41396. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41397. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41398. if (needRebuild) {
  41399. defines.rebuild();
  41400. }
  41401. return needNormals;
  41402. };
  41403. /**
  41404. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41405. * that won t be acctive due to defines being turned off.
  41406. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41407. * @param samplersList The samplers list
  41408. * @param defines The defines helping in the list generation
  41409. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41410. */
  41411. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41412. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41413. var uniformsList;
  41414. var uniformBuffersList = null;
  41415. if (uniformsListOrOptions.uniformsNames) {
  41416. var options = uniformsListOrOptions;
  41417. uniformsList = options.uniformsNames;
  41418. uniformBuffersList = options.uniformBuffersNames;
  41419. samplersList = options.samplers;
  41420. defines = options.defines;
  41421. maxSimultaneousLights = options.maxSimultaneousLights;
  41422. }
  41423. else {
  41424. uniformsList = uniformsListOrOptions;
  41425. if (!samplersList) {
  41426. samplersList = [];
  41427. }
  41428. }
  41429. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41430. if (!defines["LIGHT" + lightIndex]) {
  41431. break;
  41432. }
  41433. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41434. if (uniformBuffersList) {
  41435. uniformBuffersList.push("Light" + lightIndex);
  41436. }
  41437. samplersList.push("shadowSampler" + lightIndex);
  41438. samplersList.push("depthSampler" + lightIndex);
  41439. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41440. samplersList.push("projectionLightSampler" + lightIndex);
  41441. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41442. }
  41443. }
  41444. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41445. uniformsList.push("morphTargetInfluences");
  41446. }
  41447. };
  41448. /**
  41449. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41450. * @param defines The defines to update while falling back
  41451. * @param fallbacks The authorized effect fallbacks
  41452. * @param maxSimultaneousLights The maximum number of lights allowed
  41453. * @param rank the current rank of the Effect
  41454. * @returns The newly affected rank
  41455. */
  41456. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41457. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41458. if (rank === void 0) { rank = 0; }
  41459. var lightFallbackRank = 0;
  41460. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41461. if (!defines["LIGHT" + lightIndex]) {
  41462. break;
  41463. }
  41464. if (lightIndex > 0) {
  41465. lightFallbackRank = rank + lightIndex;
  41466. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41467. }
  41468. if (!defines["SHADOWS"]) {
  41469. if (defines["SHADOW" + lightIndex]) {
  41470. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41471. }
  41472. if (defines["SHADOWPCF" + lightIndex]) {
  41473. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41474. }
  41475. if (defines["SHADOWPCSS" + lightIndex]) {
  41476. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41477. }
  41478. if (defines["SHADOWPOISSON" + lightIndex]) {
  41479. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41480. }
  41481. if (defines["SHADOWESM" + lightIndex]) {
  41482. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41483. }
  41484. }
  41485. }
  41486. return lightFallbackRank++;
  41487. };
  41488. /**
  41489. * Prepares the list of attributes required for morph targets according to the effect defines.
  41490. * @param attribs The current list of supported attribs
  41491. * @param mesh The mesh to prepare the morph targets attributes for
  41492. * @param defines The current Defines of the effect
  41493. */
  41494. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41495. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41496. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41497. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41498. var manager = mesh.morphTargetManager;
  41499. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41500. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41501. for (var index = 0; index < influencers; index++) {
  41502. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41503. if (normal) {
  41504. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41505. }
  41506. if (tangent) {
  41507. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41508. }
  41509. if (attribs.length > maxAttributesCount) {
  41510. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41511. }
  41512. }
  41513. }
  41514. };
  41515. /**
  41516. * Prepares the list of attributes required for bones according to the effect defines.
  41517. * @param attribs The current list of supported attribs
  41518. * @param mesh The mesh to prepare the bones attributes for
  41519. * @param defines The current Defines of the effect
  41520. * @param fallbacks The current efffect fallback strategy
  41521. */
  41522. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41523. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41524. fallbacks.addCPUSkinningFallback(0, mesh);
  41525. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41526. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41527. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41528. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41529. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41530. }
  41531. }
  41532. };
  41533. /**
  41534. * Prepares the list of attributes required for instances according to the effect defines.
  41535. * @param attribs The current list of supported attribs
  41536. * @param defines The current Defines of the effect
  41537. */
  41538. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41539. if (defines["INSTANCES"]) {
  41540. attribs.push("world0");
  41541. attribs.push("world1");
  41542. attribs.push("world2");
  41543. attribs.push("world3");
  41544. }
  41545. };
  41546. /**
  41547. * Binds the light shadow information to the effect for the given mesh.
  41548. * @param light The light containing the generator
  41549. * @param scene The scene the lights belongs to
  41550. * @param mesh The mesh we are binding the information to render
  41551. * @param lightIndex The light index in the effect used to render the mesh
  41552. * @param effect The effect we are binding the data to
  41553. */
  41554. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41555. if (light.shadowEnabled && mesh.receiveShadows) {
  41556. var shadowGenerator = light.getShadowGenerator();
  41557. if (shadowGenerator) {
  41558. shadowGenerator.bindShadowLight(lightIndex, effect);
  41559. }
  41560. }
  41561. };
  41562. /**
  41563. * Binds the light information to the effect.
  41564. * @param light The light containing the generator
  41565. * @param effect The effect we are binding the data to
  41566. * @param lightIndex The light index in the effect used to render
  41567. */
  41568. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41569. light.transferToEffect(effect, lightIndex + "");
  41570. };
  41571. /**
  41572. * Binds the lights information from the scene to the effect for the given mesh.
  41573. * @param scene The scene the lights belongs to
  41574. * @param mesh The mesh we are binding the information to render
  41575. * @param effect The effect we are binding the data to
  41576. * @param defines The generated defines for the effect
  41577. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41578. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41579. */
  41580. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41581. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41582. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41583. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41584. for (var i = 0; i < len; i++) {
  41585. var light = mesh._lightSources[i];
  41586. var iAsString = i.toString();
  41587. var scaledIntensity = light.getScaledIntensity();
  41588. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41589. MaterialHelper.BindLightProperties(light, effect, i);
  41590. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41591. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41592. if (defines["SPECULARTERM"]) {
  41593. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41594. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41595. }
  41596. // Shadows
  41597. if (scene.shadowsEnabled) {
  41598. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41599. }
  41600. light._uniformBuffer.update();
  41601. }
  41602. };
  41603. /**
  41604. * Binds the fog information from the scene to the effect for the given mesh.
  41605. * @param scene The scene the lights belongs to
  41606. * @param mesh The mesh we are binding the information to render
  41607. * @param effect The effect we are binding the data to
  41608. */
  41609. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41610. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41611. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41612. effect.setColor3("vFogColor", scene.fogColor);
  41613. }
  41614. };
  41615. /**
  41616. * Binds the bones information from the mesh to the effect.
  41617. * @param mesh The mesh we are binding the information to render
  41618. * @param effect The effect we are binding the data to
  41619. */
  41620. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41621. if (!effect || !mesh) {
  41622. return;
  41623. }
  41624. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41625. mesh.computeBonesUsingShaders = false;
  41626. }
  41627. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41628. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41629. if (matrices) {
  41630. effect.setMatrices("mBones", matrices);
  41631. }
  41632. }
  41633. };
  41634. /**
  41635. * Binds the morph targets information from the mesh to the effect.
  41636. * @param abstractMesh The mesh we are binding the information to render
  41637. * @param effect The effect we are binding the data to
  41638. */
  41639. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41640. var manager = abstractMesh.morphTargetManager;
  41641. if (!abstractMesh || !manager) {
  41642. return;
  41643. }
  41644. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41645. };
  41646. /**
  41647. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41648. * @param defines The generated defines used in the effect
  41649. * @param effect The effect we are binding the data to
  41650. * @param scene The scene we are willing to render with logarithmic scale for
  41651. */
  41652. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41653. if (defines["LOGARITHMICDEPTH"]) {
  41654. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41655. }
  41656. };
  41657. /**
  41658. * Binds the clip plane information from the scene to the effect.
  41659. * @param scene The scene the clip plane information are extracted from
  41660. * @param effect The effect we are binding the data to
  41661. */
  41662. MaterialHelper.BindClipPlane = function (effect, scene) {
  41663. if (scene.clipPlane) {
  41664. var clipPlane = scene.clipPlane;
  41665. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41666. }
  41667. };
  41668. return MaterialHelper;
  41669. }());
  41670. BABYLON.MaterialHelper = MaterialHelper;
  41671. })(BABYLON || (BABYLON = {}));
  41672. //# sourceMappingURL=babylon.materialHelper.js.map
  41673. var BABYLON;
  41674. (function (BABYLON) {
  41675. var PushMaterial = /** @class */ (function (_super) {
  41676. __extends(PushMaterial, _super);
  41677. function PushMaterial(name, scene) {
  41678. var _this = _super.call(this, name, scene) || this;
  41679. _this._normalMatrix = new BABYLON.Matrix();
  41680. _this.storeEffectOnSubMeshes = true;
  41681. return _this;
  41682. }
  41683. PushMaterial.prototype.getEffect = function () {
  41684. return this._activeEffect;
  41685. };
  41686. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41687. if (!mesh) {
  41688. return false;
  41689. }
  41690. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41691. return true;
  41692. }
  41693. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41694. };
  41695. /**
  41696. * Binds the given world matrix to the active effect
  41697. *
  41698. * @param world the matrix to bind
  41699. */
  41700. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41701. this._activeEffect.setMatrix("world", world);
  41702. };
  41703. /**
  41704. * Binds the given normal matrix to the active effect
  41705. *
  41706. * @param normalMatrix the matrix to bind
  41707. */
  41708. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41709. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41710. };
  41711. PushMaterial.prototype.bind = function (world, mesh) {
  41712. if (!mesh) {
  41713. return;
  41714. }
  41715. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41716. };
  41717. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41718. if (effect === void 0) { effect = null; }
  41719. _super.prototype._afterBind.call(this, mesh);
  41720. this.getScene()._cachedEffect = effect;
  41721. };
  41722. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41723. if (visibility === void 0) { visibility = 1; }
  41724. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41725. };
  41726. return PushMaterial;
  41727. }(BABYLON.Material));
  41728. BABYLON.PushMaterial = PushMaterial;
  41729. })(BABYLON || (BABYLON = {}));
  41730. //# sourceMappingURL=babylon.pushMaterial.js.map
  41731. var BABYLON;
  41732. (function (BABYLON) {
  41733. /** @hidden */
  41734. var StandardMaterialDefines = /** @class */ (function (_super) {
  41735. __extends(StandardMaterialDefines, _super);
  41736. function StandardMaterialDefines() {
  41737. var _this = _super.call(this) || this;
  41738. _this.MAINUV1 = false;
  41739. _this.MAINUV2 = false;
  41740. _this.DIFFUSE = false;
  41741. _this.DIFFUSEDIRECTUV = 0;
  41742. _this.AMBIENT = false;
  41743. _this.AMBIENTDIRECTUV = 0;
  41744. _this.OPACITY = false;
  41745. _this.OPACITYDIRECTUV = 0;
  41746. _this.OPACITYRGB = false;
  41747. _this.REFLECTION = false;
  41748. _this.EMISSIVE = false;
  41749. _this.EMISSIVEDIRECTUV = 0;
  41750. _this.SPECULAR = false;
  41751. _this.SPECULARDIRECTUV = 0;
  41752. _this.BUMP = false;
  41753. _this.BUMPDIRECTUV = 0;
  41754. _this.PARALLAX = false;
  41755. _this.PARALLAXOCCLUSION = false;
  41756. _this.SPECULAROVERALPHA = false;
  41757. _this.CLIPPLANE = false;
  41758. _this.ALPHATEST = false;
  41759. _this.DEPTHPREPASS = false;
  41760. _this.ALPHAFROMDIFFUSE = false;
  41761. _this.POINTSIZE = false;
  41762. _this.FOG = false;
  41763. _this.SPECULARTERM = false;
  41764. _this.DIFFUSEFRESNEL = false;
  41765. _this.OPACITYFRESNEL = false;
  41766. _this.REFLECTIONFRESNEL = false;
  41767. _this.REFRACTIONFRESNEL = false;
  41768. _this.EMISSIVEFRESNEL = false;
  41769. _this.FRESNEL = false;
  41770. _this.NORMAL = false;
  41771. _this.UV1 = false;
  41772. _this.UV2 = false;
  41773. _this.VERTEXCOLOR = false;
  41774. _this.VERTEXALPHA = false;
  41775. _this.NUM_BONE_INFLUENCERS = 0;
  41776. _this.BonesPerMesh = 0;
  41777. _this.INSTANCES = false;
  41778. _this.GLOSSINESS = false;
  41779. _this.ROUGHNESS = false;
  41780. _this.EMISSIVEASILLUMINATION = false;
  41781. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41782. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41783. _this.LIGHTMAP = false;
  41784. _this.LIGHTMAPDIRECTUV = 0;
  41785. _this.OBJECTSPACE_NORMALMAP = false;
  41786. _this.USELIGHTMAPASSHADOWMAP = false;
  41787. _this.REFLECTIONMAP_3D = false;
  41788. _this.REFLECTIONMAP_SPHERICAL = false;
  41789. _this.REFLECTIONMAP_PLANAR = false;
  41790. _this.REFLECTIONMAP_CUBIC = false;
  41791. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41792. _this.REFLECTIONMAP_PROJECTION = false;
  41793. _this.REFLECTIONMAP_SKYBOX = false;
  41794. _this.REFLECTIONMAP_EXPLICIT = false;
  41795. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41796. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41797. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41798. _this.INVERTCUBICMAP = false;
  41799. _this.LOGARITHMICDEPTH = false;
  41800. _this.REFRACTION = false;
  41801. _this.REFRACTIONMAP_3D = false;
  41802. _this.REFLECTIONOVERALPHA = false;
  41803. _this.TWOSIDEDLIGHTING = false;
  41804. _this.SHADOWFLOAT = false;
  41805. _this.MORPHTARGETS = false;
  41806. _this.MORPHTARGETS_NORMAL = false;
  41807. _this.MORPHTARGETS_TANGENT = false;
  41808. _this.NUM_MORPH_INFLUENCERS = 0;
  41809. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41810. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41811. _this.IMAGEPROCESSING = false;
  41812. _this.VIGNETTE = false;
  41813. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41814. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41815. _this.TONEMAPPING = false;
  41816. _this.CONTRAST = false;
  41817. _this.COLORCURVES = false;
  41818. _this.COLORGRADING = false;
  41819. _this.COLORGRADING3D = false;
  41820. _this.SAMPLER3DGREENDEPTH = false;
  41821. _this.SAMPLER3DBGRMAP = false;
  41822. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41823. /**
  41824. * If the reflection texture on this material is in linear color space
  41825. * @hidden
  41826. */
  41827. _this.IS_REFLECTION_LINEAR = false;
  41828. /**
  41829. * If the refraction texture on this material is in linear color space
  41830. * @hidden
  41831. */
  41832. _this.IS_REFRACTION_LINEAR = false;
  41833. _this.EXPOSURE = false;
  41834. _this.rebuild();
  41835. return _this;
  41836. }
  41837. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41838. var modes = [
  41839. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41840. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41841. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41842. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41843. ];
  41844. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41845. var mode = modes_1[_i];
  41846. this[mode] = (mode === modeToEnable);
  41847. }
  41848. };
  41849. return StandardMaterialDefines;
  41850. }(BABYLON.MaterialDefines));
  41851. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41852. var StandardMaterial = /** @class */ (function (_super) {
  41853. __extends(StandardMaterial, _super);
  41854. function StandardMaterial(name, scene) {
  41855. var _this = _super.call(this, name, scene) || this;
  41856. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41857. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41858. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41859. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41860. _this.specularPower = 64;
  41861. _this._useAlphaFromDiffuseTexture = false;
  41862. _this._useEmissiveAsIllumination = false;
  41863. _this._linkEmissiveWithDiffuse = false;
  41864. _this._useSpecularOverAlpha = false;
  41865. _this._useReflectionOverAlpha = false;
  41866. _this._disableLighting = false;
  41867. _this._useObjectSpaceNormalMap = false;
  41868. _this._useParallax = false;
  41869. _this._useParallaxOcclusion = false;
  41870. _this.parallaxScaleBias = 0.05;
  41871. _this._roughness = 0;
  41872. _this.indexOfRefraction = 0.98;
  41873. _this.invertRefractionY = true;
  41874. /**
  41875. * Defines the alpha limits in alpha test mode
  41876. */
  41877. _this.alphaCutOff = 0.4;
  41878. _this._useLightmapAsShadowmap = false;
  41879. _this._useReflectionFresnelFromSpecular = false;
  41880. _this._useGlossinessFromSpecularMapAlpha = false;
  41881. _this._maxSimultaneousLights = 4;
  41882. /**
  41883. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41884. */
  41885. _this._invertNormalMapX = false;
  41886. /**
  41887. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41888. */
  41889. _this._invertNormalMapY = false;
  41890. /**
  41891. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41892. */
  41893. _this._twoSidedLighting = false;
  41894. _this._renderTargets = new BABYLON.SmartArray(16);
  41895. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41896. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41897. // Setup the default processing configuration to the scene.
  41898. _this._attachImageProcessingConfiguration(null);
  41899. _this.getRenderTargetTextures = function () {
  41900. _this._renderTargets.reset();
  41901. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41902. _this._renderTargets.push(_this._reflectionTexture);
  41903. }
  41904. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41905. _this._renderTargets.push(_this._refractionTexture);
  41906. }
  41907. return _this._renderTargets;
  41908. };
  41909. return _this;
  41910. }
  41911. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41912. /**
  41913. * Gets the image processing configuration used either in this material.
  41914. */
  41915. get: function () {
  41916. return this._imageProcessingConfiguration;
  41917. },
  41918. /**
  41919. * Sets the Default image processing configuration used either in the this material.
  41920. *
  41921. * If sets to null, the scene one is in use.
  41922. */
  41923. set: function (value) {
  41924. this._attachImageProcessingConfiguration(value);
  41925. // Ensure the effect will be rebuilt.
  41926. this._markAllSubMeshesAsTexturesDirty();
  41927. },
  41928. enumerable: true,
  41929. configurable: true
  41930. });
  41931. /**
  41932. * Attaches a new image processing configuration to the Standard Material.
  41933. * @param configuration
  41934. */
  41935. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41936. var _this = this;
  41937. if (configuration === this._imageProcessingConfiguration) {
  41938. return;
  41939. }
  41940. // Detaches observer.
  41941. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41942. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41943. }
  41944. // Pick the scene configuration if needed.
  41945. if (!configuration) {
  41946. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41947. }
  41948. else {
  41949. this._imageProcessingConfiguration = configuration;
  41950. }
  41951. // Attaches observer.
  41952. if (this._imageProcessingConfiguration) {
  41953. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41954. _this._markAllSubMeshesAsImageProcessingDirty();
  41955. });
  41956. }
  41957. };
  41958. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41959. /**
  41960. * Gets wether the color curves effect is enabled.
  41961. */
  41962. get: function () {
  41963. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41964. },
  41965. /**
  41966. * Sets wether the color curves effect is enabled.
  41967. */
  41968. set: function (value) {
  41969. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41970. },
  41971. enumerable: true,
  41972. configurable: true
  41973. });
  41974. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41975. /**
  41976. * Gets wether the color grading effect is enabled.
  41977. */
  41978. get: function () {
  41979. return this.imageProcessingConfiguration.colorGradingEnabled;
  41980. },
  41981. /**
  41982. * Gets wether the color grading effect is enabled.
  41983. */
  41984. set: function (value) {
  41985. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41986. },
  41987. enumerable: true,
  41988. configurable: true
  41989. });
  41990. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41991. /**
  41992. * Gets wether tonemapping is enabled or not.
  41993. */
  41994. get: function () {
  41995. return this._imageProcessingConfiguration.toneMappingEnabled;
  41996. },
  41997. /**
  41998. * Sets wether tonemapping is enabled or not
  41999. */
  42000. set: function (value) {
  42001. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42002. },
  42003. enumerable: true,
  42004. configurable: true
  42005. });
  42006. ;
  42007. ;
  42008. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42009. /**
  42010. * The camera exposure used on this material.
  42011. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42012. * This corresponds to a photographic exposure.
  42013. */
  42014. get: function () {
  42015. return this._imageProcessingConfiguration.exposure;
  42016. },
  42017. /**
  42018. * The camera exposure used on this material.
  42019. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42020. * This corresponds to a photographic exposure.
  42021. */
  42022. set: function (value) {
  42023. this._imageProcessingConfiguration.exposure = value;
  42024. },
  42025. enumerable: true,
  42026. configurable: true
  42027. });
  42028. ;
  42029. ;
  42030. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42031. /**
  42032. * Gets The camera contrast used on this material.
  42033. */
  42034. get: function () {
  42035. return this._imageProcessingConfiguration.contrast;
  42036. },
  42037. /**
  42038. * Sets The camera contrast used on this material.
  42039. */
  42040. set: function (value) {
  42041. this._imageProcessingConfiguration.contrast = value;
  42042. },
  42043. enumerable: true,
  42044. configurable: true
  42045. });
  42046. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42047. /**
  42048. * Gets the Color Grading 2D Lookup Texture.
  42049. */
  42050. get: function () {
  42051. return this._imageProcessingConfiguration.colorGradingTexture;
  42052. },
  42053. /**
  42054. * Sets the Color Grading 2D Lookup Texture.
  42055. */
  42056. set: function (value) {
  42057. this._imageProcessingConfiguration.colorGradingTexture = value;
  42058. },
  42059. enumerable: true,
  42060. configurable: true
  42061. });
  42062. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42063. /**
  42064. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42065. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42066. * 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;
  42067. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42068. */
  42069. get: function () {
  42070. return this._imageProcessingConfiguration.colorCurves;
  42071. },
  42072. /**
  42073. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42074. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42075. * 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;
  42076. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42077. */
  42078. set: function (value) {
  42079. this._imageProcessingConfiguration.colorCurves = value;
  42080. },
  42081. enumerable: true,
  42082. configurable: true
  42083. });
  42084. StandardMaterial.prototype.getClassName = function () {
  42085. return "StandardMaterial";
  42086. };
  42087. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42088. get: function () {
  42089. return this._useLogarithmicDepth;
  42090. },
  42091. set: function (value) {
  42092. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42093. this._markAllSubMeshesAsMiscDirty();
  42094. },
  42095. enumerable: true,
  42096. configurable: true
  42097. });
  42098. StandardMaterial.prototype.needAlphaBlending = function () {
  42099. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42100. };
  42101. StandardMaterial.prototype.needAlphaTesting = function () {
  42102. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42103. };
  42104. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42105. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42106. };
  42107. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42108. return this._diffuseTexture;
  42109. };
  42110. /**
  42111. * Child classes can use it to update shaders
  42112. */
  42113. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42114. if (useInstances === void 0) { useInstances = false; }
  42115. if (subMesh.effect && this.isFrozen) {
  42116. if (this._wasPreviouslyReady && subMesh.effect) {
  42117. return true;
  42118. }
  42119. }
  42120. if (!subMesh._materialDefines) {
  42121. subMesh._materialDefines = new StandardMaterialDefines();
  42122. }
  42123. var scene = this.getScene();
  42124. var defines = subMesh._materialDefines;
  42125. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42126. if (defines._renderId === scene.getRenderId()) {
  42127. return true;
  42128. }
  42129. }
  42130. var engine = scene.getEngine();
  42131. // Lights
  42132. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42133. // Textures
  42134. if (defines._areTexturesDirty) {
  42135. defines._needUVs = false;
  42136. defines.MAINUV1 = false;
  42137. defines.MAINUV2 = false;
  42138. if (scene.texturesEnabled) {
  42139. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42140. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42141. return false;
  42142. }
  42143. else {
  42144. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42145. }
  42146. }
  42147. else {
  42148. defines.DIFFUSE = false;
  42149. }
  42150. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42151. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42152. return false;
  42153. }
  42154. else {
  42155. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42156. }
  42157. }
  42158. else {
  42159. defines.AMBIENT = false;
  42160. }
  42161. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42162. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42163. return false;
  42164. }
  42165. else {
  42166. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42167. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42168. }
  42169. }
  42170. else {
  42171. defines.OPACITY = false;
  42172. }
  42173. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42174. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42175. return false;
  42176. }
  42177. else {
  42178. defines._needNormals = true;
  42179. defines.REFLECTION = true;
  42180. defines.ROUGHNESS = (this._roughness > 0);
  42181. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42182. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42183. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42184. switch (this._reflectionTexture.coordinatesMode) {
  42185. case BABYLON.Texture.EXPLICIT_MODE:
  42186. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42187. break;
  42188. case BABYLON.Texture.PLANAR_MODE:
  42189. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42190. break;
  42191. case BABYLON.Texture.PROJECTION_MODE:
  42192. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42193. break;
  42194. case BABYLON.Texture.SKYBOX_MODE:
  42195. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42196. break;
  42197. case BABYLON.Texture.SPHERICAL_MODE:
  42198. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42199. break;
  42200. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42201. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42202. break;
  42203. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42204. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42205. break;
  42206. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42207. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42208. break;
  42209. case BABYLON.Texture.CUBIC_MODE:
  42210. case BABYLON.Texture.INVCUBIC_MODE:
  42211. default:
  42212. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42213. break;
  42214. }
  42215. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42216. }
  42217. }
  42218. else {
  42219. defines.REFLECTION = false;
  42220. }
  42221. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42222. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42223. return false;
  42224. }
  42225. else {
  42226. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42227. }
  42228. }
  42229. else {
  42230. defines.EMISSIVE = false;
  42231. }
  42232. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42233. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42234. return false;
  42235. }
  42236. else {
  42237. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42238. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42239. }
  42240. }
  42241. else {
  42242. defines.LIGHTMAP = false;
  42243. }
  42244. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42245. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42246. return false;
  42247. }
  42248. else {
  42249. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42250. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42251. }
  42252. }
  42253. else {
  42254. defines.SPECULAR = false;
  42255. }
  42256. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42257. // Bump texure can not be not blocking.
  42258. if (!this._bumpTexture.isReady()) {
  42259. return false;
  42260. }
  42261. else {
  42262. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42263. defines.PARALLAX = this._useParallax;
  42264. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42265. }
  42266. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42267. }
  42268. else {
  42269. defines.BUMP = false;
  42270. }
  42271. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42272. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42273. return false;
  42274. }
  42275. else {
  42276. defines._needUVs = true;
  42277. defines.REFRACTION = true;
  42278. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42279. }
  42280. }
  42281. else {
  42282. defines.REFRACTION = false;
  42283. }
  42284. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42285. }
  42286. else {
  42287. defines.DIFFUSE = false;
  42288. defines.AMBIENT = false;
  42289. defines.OPACITY = false;
  42290. defines.REFLECTION = false;
  42291. defines.EMISSIVE = false;
  42292. defines.LIGHTMAP = false;
  42293. defines.BUMP = false;
  42294. defines.REFRACTION = false;
  42295. }
  42296. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42297. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42298. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42299. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42300. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42301. }
  42302. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42303. if (!this._imageProcessingConfiguration.isReady()) {
  42304. return false;
  42305. }
  42306. this._imageProcessingConfiguration.prepareDefines(defines);
  42307. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42308. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42309. }
  42310. if (defines._areFresnelDirty) {
  42311. if (StandardMaterial.FresnelEnabled) {
  42312. // Fresnel
  42313. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42314. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42315. this._reflectionFresnelParameters) {
  42316. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42317. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42318. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42319. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42320. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42321. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42322. defines._needNormals = true;
  42323. defines.FRESNEL = true;
  42324. }
  42325. }
  42326. else {
  42327. defines.FRESNEL = false;
  42328. }
  42329. }
  42330. // Misc.
  42331. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42332. // Attribs
  42333. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42334. // Values that need to be evaluated on every frame
  42335. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42336. // Get correct effect
  42337. if (defines.isDirty) {
  42338. defines.markAsProcessed();
  42339. scene.resetCachedMaterial();
  42340. // Fallbacks
  42341. var fallbacks = new BABYLON.EffectFallbacks();
  42342. if (defines.REFLECTION) {
  42343. fallbacks.addFallback(0, "REFLECTION");
  42344. }
  42345. if (defines.SPECULAR) {
  42346. fallbacks.addFallback(0, "SPECULAR");
  42347. }
  42348. if (defines.BUMP) {
  42349. fallbacks.addFallback(0, "BUMP");
  42350. }
  42351. if (defines.PARALLAX) {
  42352. fallbacks.addFallback(1, "PARALLAX");
  42353. }
  42354. if (defines.PARALLAXOCCLUSION) {
  42355. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42356. }
  42357. if (defines.SPECULAROVERALPHA) {
  42358. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42359. }
  42360. if (defines.FOG) {
  42361. fallbacks.addFallback(1, "FOG");
  42362. }
  42363. if (defines.POINTSIZE) {
  42364. fallbacks.addFallback(0, "POINTSIZE");
  42365. }
  42366. if (defines.LOGARITHMICDEPTH) {
  42367. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42368. }
  42369. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42370. if (defines.SPECULARTERM) {
  42371. fallbacks.addFallback(0, "SPECULARTERM");
  42372. }
  42373. if (defines.DIFFUSEFRESNEL) {
  42374. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42375. }
  42376. if (defines.OPACITYFRESNEL) {
  42377. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42378. }
  42379. if (defines.REFLECTIONFRESNEL) {
  42380. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42381. }
  42382. if (defines.EMISSIVEFRESNEL) {
  42383. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42384. }
  42385. if (defines.FRESNEL) {
  42386. fallbacks.addFallback(4, "FRESNEL");
  42387. }
  42388. //Attributes
  42389. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42390. if (defines.NORMAL) {
  42391. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42392. }
  42393. if (defines.UV1) {
  42394. attribs.push(BABYLON.VertexBuffer.UVKind);
  42395. }
  42396. if (defines.UV2) {
  42397. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42398. }
  42399. if (defines.VERTEXCOLOR) {
  42400. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42401. }
  42402. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42403. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42404. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42405. var shaderName = "default";
  42406. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42407. "vFogInfos", "vFogColor", "pointSize",
  42408. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42409. "mBones",
  42410. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42411. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42412. "vReflectionPosition", "vReflectionSize",
  42413. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42414. ];
  42415. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42416. var uniformBuffers = ["Material", "Scene"];
  42417. if (BABYLON.ImageProcessingConfiguration) {
  42418. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42419. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42420. }
  42421. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42422. uniformsNames: uniforms,
  42423. uniformBuffersNames: uniformBuffers,
  42424. samplers: samplers,
  42425. defines: defines,
  42426. maxSimultaneousLights: this._maxSimultaneousLights
  42427. });
  42428. if (this.customShaderNameResolve) {
  42429. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42430. }
  42431. var join = defines.toString();
  42432. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42433. attributes: attribs,
  42434. uniformsNames: uniforms,
  42435. uniformBuffersNames: uniformBuffers,
  42436. samplers: samplers,
  42437. defines: join,
  42438. fallbacks: fallbacks,
  42439. onCompiled: this.onCompiled,
  42440. onError: this.onError,
  42441. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42442. }, engine), defines);
  42443. this.buildUniformLayout();
  42444. }
  42445. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42446. return false;
  42447. }
  42448. defines._renderId = scene.getRenderId();
  42449. this._wasPreviouslyReady = true;
  42450. return true;
  42451. };
  42452. StandardMaterial.prototype.buildUniformLayout = function () {
  42453. // Order is important !
  42454. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42455. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42456. this._uniformBuffer.addUniform("opacityParts", 4);
  42457. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42458. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42459. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42460. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42461. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42462. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42463. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42464. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42465. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42466. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42467. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42468. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42469. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42470. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42471. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42472. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42473. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42474. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42475. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42476. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42477. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42478. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42479. this._uniformBuffer.addUniform("specularMatrix", 16);
  42480. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42481. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42482. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42483. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42484. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42485. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42486. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42487. this._uniformBuffer.addUniform("pointSize", 1);
  42488. this._uniformBuffer.create();
  42489. };
  42490. StandardMaterial.prototype.unbind = function () {
  42491. if (this._activeEffect) {
  42492. var needFlag = false;
  42493. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42494. this._activeEffect.setTexture("reflection2DSampler", null);
  42495. needFlag = true;
  42496. }
  42497. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42498. this._activeEffect.setTexture("refraction2DSampler", null);
  42499. needFlag = true;
  42500. }
  42501. if (needFlag) {
  42502. this._markAllSubMeshesAsTexturesDirty();
  42503. }
  42504. }
  42505. _super.prototype.unbind.call(this);
  42506. };
  42507. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42508. var scene = this.getScene();
  42509. var defines = subMesh._materialDefines;
  42510. if (!defines) {
  42511. return;
  42512. }
  42513. var effect = subMesh.effect;
  42514. if (!effect) {
  42515. return;
  42516. }
  42517. this._activeEffect = effect;
  42518. // Matrices
  42519. this.bindOnlyWorldMatrix(world);
  42520. // Normal Matrix
  42521. if (defines.OBJECTSPACE_NORMALMAP) {
  42522. world.toNormalMatrix(this._normalMatrix);
  42523. this.bindOnlyNormalMatrix(this._normalMatrix);
  42524. }
  42525. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42526. // Bones
  42527. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42528. if (mustRebind) {
  42529. this._uniformBuffer.bindToEffect(effect, "Material");
  42530. this.bindViewProjection(effect);
  42531. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42532. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42533. // Fresnel
  42534. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42535. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42536. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42537. }
  42538. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42539. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42540. }
  42541. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42542. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42543. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42544. }
  42545. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42546. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42547. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42548. }
  42549. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42550. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42551. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42552. }
  42553. }
  42554. // Textures
  42555. if (scene.texturesEnabled) {
  42556. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42557. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42558. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42559. if (this._diffuseTexture.hasAlpha) {
  42560. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42561. }
  42562. }
  42563. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42564. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42565. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42566. }
  42567. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42568. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42569. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42570. }
  42571. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42572. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42573. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42574. if (this._reflectionTexture.boundingBoxSize) {
  42575. var cubeTexture = this._reflectionTexture;
  42576. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42577. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42578. }
  42579. }
  42580. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42581. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42582. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42583. }
  42584. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42585. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42586. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42587. }
  42588. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42589. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42590. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42591. }
  42592. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42593. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42594. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42595. if (scene._mirroredCameraPosition) {
  42596. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42597. }
  42598. else {
  42599. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42600. }
  42601. }
  42602. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42603. var depth = 1.0;
  42604. if (!this._refractionTexture.isCube) {
  42605. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42606. if (this._refractionTexture.depth) {
  42607. depth = this._refractionTexture.depth;
  42608. }
  42609. }
  42610. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42611. }
  42612. }
  42613. // Point size
  42614. if (this.pointsCloud) {
  42615. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42616. }
  42617. if (defines.SPECULARTERM) {
  42618. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42619. }
  42620. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42621. // Diffuse
  42622. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42623. }
  42624. // Textures
  42625. if (scene.texturesEnabled) {
  42626. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42627. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42628. }
  42629. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42630. effect.setTexture("ambientSampler", this._ambientTexture);
  42631. }
  42632. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42633. effect.setTexture("opacitySampler", this._opacityTexture);
  42634. }
  42635. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42636. if (this._reflectionTexture.isCube) {
  42637. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42638. }
  42639. else {
  42640. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42641. }
  42642. }
  42643. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42644. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42645. }
  42646. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42647. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42648. }
  42649. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42650. effect.setTexture("specularSampler", this._specularTexture);
  42651. }
  42652. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42653. effect.setTexture("bumpSampler", this._bumpTexture);
  42654. }
  42655. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42656. var depth = 1.0;
  42657. if (this._refractionTexture.isCube) {
  42658. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42659. }
  42660. else {
  42661. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42662. }
  42663. }
  42664. }
  42665. // Clip plane
  42666. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42667. // Colors
  42668. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42669. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42670. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42671. }
  42672. if (mustRebind || !this.isFrozen) {
  42673. // Lights
  42674. if (scene.lightsEnabled && !this._disableLighting) {
  42675. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42676. }
  42677. // View
  42678. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42679. this.bindView(effect);
  42680. }
  42681. // Fog
  42682. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42683. // Morph targets
  42684. if (defines.NUM_MORPH_INFLUENCERS) {
  42685. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42686. }
  42687. // Log. depth
  42688. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42689. // image processing
  42690. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42691. this._imageProcessingConfiguration.bind(this._activeEffect);
  42692. }
  42693. }
  42694. this._uniformBuffer.update();
  42695. this._afterBind(mesh, this._activeEffect);
  42696. };
  42697. StandardMaterial.prototype.getAnimatables = function () {
  42698. var results = [];
  42699. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42700. results.push(this._diffuseTexture);
  42701. }
  42702. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42703. results.push(this._ambientTexture);
  42704. }
  42705. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42706. results.push(this._opacityTexture);
  42707. }
  42708. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42709. results.push(this._reflectionTexture);
  42710. }
  42711. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42712. results.push(this._emissiveTexture);
  42713. }
  42714. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42715. results.push(this._specularTexture);
  42716. }
  42717. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42718. results.push(this._bumpTexture);
  42719. }
  42720. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42721. results.push(this._lightmapTexture);
  42722. }
  42723. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42724. results.push(this._refractionTexture);
  42725. }
  42726. return results;
  42727. };
  42728. StandardMaterial.prototype.getActiveTextures = function () {
  42729. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42730. if (this._diffuseTexture) {
  42731. activeTextures.push(this._diffuseTexture);
  42732. }
  42733. if (this._ambientTexture) {
  42734. activeTextures.push(this._ambientTexture);
  42735. }
  42736. if (this._opacityTexture) {
  42737. activeTextures.push(this._opacityTexture);
  42738. }
  42739. if (this._reflectionTexture) {
  42740. activeTextures.push(this._reflectionTexture);
  42741. }
  42742. if (this._emissiveTexture) {
  42743. activeTextures.push(this._emissiveTexture);
  42744. }
  42745. if (this._specularTexture) {
  42746. activeTextures.push(this._specularTexture);
  42747. }
  42748. if (this._bumpTexture) {
  42749. activeTextures.push(this._bumpTexture);
  42750. }
  42751. if (this._lightmapTexture) {
  42752. activeTextures.push(this._lightmapTexture);
  42753. }
  42754. if (this._refractionTexture) {
  42755. activeTextures.push(this._refractionTexture);
  42756. }
  42757. return activeTextures;
  42758. };
  42759. StandardMaterial.prototype.hasTexture = function (texture) {
  42760. if (_super.prototype.hasTexture.call(this, texture)) {
  42761. return true;
  42762. }
  42763. if (this._diffuseTexture === texture) {
  42764. return true;
  42765. }
  42766. if (this._ambientTexture === texture) {
  42767. return true;
  42768. }
  42769. if (this._opacityTexture === texture) {
  42770. return true;
  42771. }
  42772. if (this._reflectionTexture === texture) {
  42773. return true;
  42774. }
  42775. if (this._emissiveTexture === texture) {
  42776. return true;
  42777. }
  42778. if (this._specularTexture === texture) {
  42779. return true;
  42780. }
  42781. if (this._bumpTexture === texture) {
  42782. return true;
  42783. }
  42784. if (this._lightmapTexture === texture) {
  42785. return true;
  42786. }
  42787. if (this._refractionTexture === texture) {
  42788. return true;
  42789. }
  42790. return false;
  42791. };
  42792. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42793. if (forceDisposeTextures) {
  42794. if (this._diffuseTexture) {
  42795. this._diffuseTexture.dispose();
  42796. }
  42797. if (this._ambientTexture) {
  42798. this._ambientTexture.dispose();
  42799. }
  42800. if (this._opacityTexture) {
  42801. this._opacityTexture.dispose();
  42802. }
  42803. if (this._reflectionTexture) {
  42804. this._reflectionTexture.dispose();
  42805. }
  42806. if (this._emissiveTexture) {
  42807. this._emissiveTexture.dispose();
  42808. }
  42809. if (this._specularTexture) {
  42810. this._specularTexture.dispose();
  42811. }
  42812. if (this._bumpTexture) {
  42813. this._bumpTexture.dispose();
  42814. }
  42815. if (this._lightmapTexture) {
  42816. this._lightmapTexture.dispose();
  42817. }
  42818. if (this._refractionTexture) {
  42819. this._refractionTexture.dispose();
  42820. }
  42821. }
  42822. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42823. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42824. }
  42825. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42826. };
  42827. StandardMaterial.prototype.clone = function (name) {
  42828. var _this = this;
  42829. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42830. result.name = name;
  42831. result.id = name;
  42832. return result;
  42833. };
  42834. StandardMaterial.prototype.serialize = function () {
  42835. return BABYLON.SerializationHelper.Serialize(this);
  42836. };
  42837. // Statics
  42838. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42839. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42840. };
  42841. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42842. get: function () {
  42843. return StandardMaterial._DiffuseTextureEnabled;
  42844. },
  42845. set: function (value) {
  42846. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42847. return;
  42848. }
  42849. StandardMaterial._DiffuseTextureEnabled = value;
  42850. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42851. },
  42852. enumerable: true,
  42853. configurable: true
  42854. });
  42855. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42856. get: function () {
  42857. return StandardMaterial._AmbientTextureEnabled;
  42858. },
  42859. set: function (value) {
  42860. if (StandardMaterial._AmbientTextureEnabled === value) {
  42861. return;
  42862. }
  42863. StandardMaterial._AmbientTextureEnabled = value;
  42864. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42865. },
  42866. enumerable: true,
  42867. configurable: true
  42868. });
  42869. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42870. get: function () {
  42871. return StandardMaterial._OpacityTextureEnabled;
  42872. },
  42873. set: function (value) {
  42874. if (StandardMaterial._OpacityTextureEnabled === value) {
  42875. return;
  42876. }
  42877. StandardMaterial._OpacityTextureEnabled = value;
  42878. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42879. },
  42880. enumerable: true,
  42881. configurable: true
  42882. });
  42883. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42884. get: function () {
  42885. return StandardMaterial._ReflectionTextureEnabled;
  42886. },
  42887. set: function (value) {
  42888. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42889. return;
  42890. }
  42891. StandardMaterial._ReflectionTextureEnabled = value;
  42892. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42893. },
  42894. enumerable: true,
  42895. configurable: true
  42896. });
  42897. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42898. get: function () {
  42899. return StandardMaterial._EmissiveTextureEnabled;
  42900. },
  42901. set: function (value) {
  42902. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42903. return;
  42904. }
  42905. StandardMaterial._EmissiveTextureEnabled = value;
  42906. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42907. },
  42908. enumerable: true,
  42909. configurable: true
  42910. });
  42911. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42912. get: function () {
  42913. return StandardMaterial._SpecularTextureEnabled;
  42914. },
  42915. set: function (value) {
  42916. if (StandardMaterial._SpecularTextureEnabled === value) {
  42917. return;
  42918. }
  42919. StandardMaterial._SpecularTextureEnabled = value;
  42920. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42921. },
  42922. enumerable: true,
  42923. configurable: true
  42924. });
  42925. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42926. get: function () {
  42927. return StandardMaterial._BumpTextureEnabled;
  42928. },
  42929. set: function (value) {
  42930. if (StandardMaterial._BumpTextureEnabled === value) {
  42931. return;
  42932. }
  42933. StandardMaterial._BumpTextureEnabled = value;
  42934. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42935. },
  42936. enumerable: true,
  42937. configurable: true
  42938. });
  42939. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42940. get: function () {
  42941. return StandardMaterial._LightmapTextureEnabled;
  42942. },
  42943. set: function (value) {
  42944. if (StandardMaterial._LightmapTextureEnabled === value) {
  42945. return;
  42946. }
  42947. StandardMaterial._LightmapTextureEnabled = value;
  42948. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42949. },
  42950. enumerable: true,
  42951. configurable: true
  42952. });
  42953. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42954. get: function () {
  42955. return StandardMaterial._RefractionTextureEnabled;
  42956. },
  42957. set: function (value) {
  42958. if (StandardMaterial._RefractionTextureEnabled === value) {
  42959. return;
  42960. }
  42961. StandardMaterial._RefractionTextureEnabled = value;
  42962. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42963. },
  42964. enumerable: true,
  42965. configurable: true
  42966. });
  42967. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42968. get: function () {
  42969. return StandardMaterial._ColorGradingTextureEnabled;
  42970. },
  42971. set: function (value) {
  42972. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42973. return;
  42974. }
  42975. StandardMaterial._ColorGradingTextureEnabled = value;
  42976. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42977. },
  42978. enumerable: true,
  42979. configurable: true
  42980. });
  42981. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42982. get: function () {
  42983. return StandardMaterial._FresnelEnabled;
  42984. },
  42985. set: function (value) {
  42986. if (StandardMaterial._FresnelEnabled === value) {
  42987. return;
  42988. }
  42989. StandardMaterial._FresnelEnabled = value;
  42990. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42991. },
  42992. enumerable: true,
  42993. configurable: true
  42994. });
  42995. // Flags used to enable or disable a type of texture for all Standard Materials
  42996. StandardMaterial._DiffuseTextureEnabled = true;
  42997. StandardMaterial._AmbientTextureEnabled = true;
  42998. StandardMaterial._OpacityTextureEnabled = true;
  42999. StandardMaterial._ReflectionTextureEnabled = true;
  43000. StandardMaterial._EmissiveTextureEnabled = true;
  43001. StandardMaterial._SpecularTextureEnabled = true;
  43002. StandardMaterial._BumpTextureEnabled = true;
  43003. StandardMaterial._LightmapTextureEnabled = true;
  43004. StandardMaterial._RefractionTextureEnabled = true;
  43005. StandardMaterial._ColorGradingTextureEnabled = true;
  43006. StandardMaterial._FresnelEnabled = true;
  43007. __decorate([
  43008. BABYLON.serializeAsTexture("diffuseTexture")
  43009. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43010. __decorate([
  43011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43012. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43013. __decorate([
  43014. BABYLON.serializeAsTexture("ambientTexture")
  43015. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43016. __decorate([
  43017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43018. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43019. __decorate([
  43020. BABYLON.serializeAsTexture("opacityTexture")
  43021. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43022. __decorate([
  43023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43024. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43025. __decorate([
  43026. BABYLON.serializeAsTexture("reflectionTexture")
  43027. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43028. __decorate([
  43029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43030. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43031. __decorate([
  43032. BABYLON.serializeAsTexture("emissiveTexture")
  43033. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43034. __decorate([
  43035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43036. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43037. __decorate([
  43038. BABYLON.serializeAsTexture("specularTexture")
  43039. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43040. __decorate([
  43041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43042. ], StandardMaterial.prototype, "specularTexture", void 0);
  43043. __decorate([
  43044. BABYLON.serializeAsTexture("bumpTexture")
  43045. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43046. __decorate([
  43047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43048. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43049. __decorate([
  43050. BABYLON.serializeAsTexture("lightmapTexture")
  43051. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43052. __decorate([
  43053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43054. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43055. __decorate([
  43056. BABYLON.serializeAsTexture("refractionTexture")
  43057. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43058. __decorate([
  43059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43060. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43061. __decorate([
  43062. BABYLON.serializeAsColor3("ambient")
  43063. ], StandardMaterial.prototype, "ambientColor", void 0);
  43064. __decorate([
  43065. BABYLON.serializeAsColor3("diffuse")
  43066. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43067. __decorate([
  43068. BABYLON.serializeAsColor3("specular")
  43069. ], StandardMaterial.prototype, "specularColor", void 0);
  43070. __decorate([
  43071. BABYLON.serializeAsColor3("emissive")
  43072. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43073. __decorate([
  43074. BABYLON.serialize()
  43075. ], StandardMaterial.prototype, "specularPower", void 0);
  43076. __decorate([
  43077. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43078. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43079. __decorate([
  43080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43081. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43082. __decorate([
  43083. BABYLON.serialize("useEmissiveAsIllumination")
  43084. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43085. __decorate([
  43086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43087. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43088. __decorate([
  43089. BABYLON.serialize("linkEmissiveWithDiffuse")
  43090. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43091. __decorate([
  43092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43093. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43094. __decorate([
  43095. BABYLON.serialize("useSpecularOverAlpha")
  43096. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43097. __decorate([
  43098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43099. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43100. __decorate([
  43101. BABYLON.serialize("useReflectionOverAlpha")
  43102. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43103. __decorate([
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43105. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43106. __decorate([
  43107. BABYLON.serialize("disableLighting")
  43108. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43109. __decorate([
  43110. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43111. ], StandardMaterial.prototype, "disableLighting", void 0);
  43112. __decorate([
  43113. BABYLON.serialize("useObjectSpaceNormalMap")
  43114. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43115. __decorate([
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43117. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43118. __decorate([
  43119. BABYLON.serialize("useParallax")
  43120. ], StandardMaterial.prototype, "_useParallax", void 0);
  43121. __decorate([
  43122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43123. ], StandardMaterial.prototype, "useParallax", void 0);
  43124. __decorate([
  43125. BABYLON.serialize("useParallaxOcclusion")
  43126. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43127. __decorate([
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43129. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43130. __decorate([
  43131. BABYLON.serialize()
  43132. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43133. __decorate([
  43134. BABYLON.serialize("roughness")
  43135. ], StandardMaterial.prototype, "_roughness", void 0);
  43136. __decorate([
  43137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43138. ], StandardMaterial.prototype, "roughness", void 0);
  43139. __decorate([
  43140. BABYLON.serialize()
  43141. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43142. __decorate([
  43143. BABYLON.serialize()
  43144. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43145. __decorate([
  43146. BABYLON.serialize()
  43147. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43148. __decorate([
  43149. BABYLON.serialize("useLightmapAsShadowmap")
  43150. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43151. __decorate([
  43152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43153. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43154. __decorate([
  43155. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43156. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43157. __decorate([
  43158. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43159. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43160. __decorate([
  43161. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43162. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43163. __decorate([
  43164. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43165. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43166. __decorate([
  43167. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43168. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43169. __decorate([
  43170. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43171. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43172. __decorate([
  43173. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43174. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43175. __decorate([
  43176. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43177. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43178. __decorate([
  43179. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43180. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43181. __decorate([
  43182. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43183. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43184. __decorate([
  43185. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43186. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43187. __decorate([
  43188. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43189. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43190. __decorate([
  43191. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43192. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43193. __decorate([
  43194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43195. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43196. __decorate([
  43197. BABYLON.serialize("maxSimultaneousLights")
  43198. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43199. __decorate([
  43200. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43201. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43202. __decorate([
  43203. BABYLON.serialize("invertNormalMapX")
  43204. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43205. __decorate([
  43206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43207. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43208. __decorate([
  43209. BABYLON.serialize("invertNormalMapY")
  43210. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43211. __decorate([
  43212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43213. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43214. __decorate([
  43215. BABYLON.serialize("twoSidedLighting")
  43216. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43217. __decorate([
  43218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43219. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43220. __decorate([
  43221. BABYLON.serialize()
  43222. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43223. return StandardMaterial;
  43224. }(BABYLON.PushMaterial));
  43225. BABYLON.StandardMaterial = StandardMaterial;
  43226. })(BABYLON || (BABYLON = {}));
  43227. //# sourceMappingURL=babylon.standardMaterial.js.map
  43228. var BABYLON;
  43229. (function (BABYLON) {
  43230. /**
  43231. * Manages the defines for the PBR Material.
  43232. * @hiddenChildren
  43233. */
  43234. var PBRMaterialDefines = /** @class */ (function (_super) {
  43235. __extends(PBRMaterialDefines, _super);
  43236. /**
  43237. * Initializes the PBR Material defines.
  43238. */
  43239. function PBRMaterialDefines() {
  43240. var _this = _super.call(this) || this;
  43241. _this.PBR = true;
  43242. _this.MAINUV1 = false;
  43243. _this.MAINUV2 = false;
  43244. _this.UV1 = false;
  43245. _this.UV2 = false;
  43246. _this.ALBEDO = false;
  43247. _this.ALBEDODIRECTUV = 0;
  43248. _this.VERTEXCOLOR = false;
  43249. _this.AMBIENT = false;
  43250. _this.AMBIENTDIRECTUV = 0;
  43251. _this.AMBIENTINGRAYSCALE = false;
  43252. _this.OPACITY = false;
  43253. _this.VERTEXALPHA = false;
  43254. _this.OPACITYDIRECTUV = 0;
  43255. _this.OPACITYRGB = false;
  43256. _this.ALPHATEST = false;
  43257. _this.DEPTHPREPASS = false;
  43258. _this.ALPHABLEND = false;
  43259. _this.ALPHAFROMALBEDO = false;
  43260. _this.ALPHATESTVALUE = "0.5";
  43261. _this.SPECULAROVERALPHA = false;
  43262. _this.RADIANCEOVERALPHA = false;
  43263. _this.ALPHAFRESNEL = false;
  43264. _this.LINEARALPHAFRESNEL = false;
  43265. _this.PREMULTIPLYALPHA = false;
  43266. _this.EMISSIVE = false;
  43267. _this.EMISSIVEDIRECTUV = 0;
  43268. _this.REFLECTIVITY = false;
  43269. _this.REFLECTIVITYDIRECTUV = 0;
  43270. _this.SPECULARTERM = false;
  43271. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43272. _this.MICROSURFACEAUTOMATIC = false;
  43273. _this.LODBASEDMICROSFURACE = false;
  43274. _this.MICROSURFACEMAP = false;
  43275. _this.MICROSURFACEMAPDIRECTUV = 0;
  43276. _this.METALLICWORKFLOW = false;
  43277. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43278. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43279. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43280. _this.AOSTOREINMETALMAPRED = false;
  43281. _this.ENVIRONMENTBRDF = false;
  43282. _this.NORMAL = false;
  43283. _this.TANGENT = false;
  43284. _this.BUMP = false;
  43285. _this.BUMPDIRECTUV = 0;
  43286. _this.OBJECTSPACE_NORMALMAP = false;
  43287. _this.PARALLAX = false;
  43288. _this.PARALLAXOCCLUSION = false;
  43289. _this.NORMALXYSCALE = true;
  43290. _this.LIGHTMAP = false;
  43291. _this.LIGHTMAPDIRECTUV = 0;
  43292. _this.USELIGHTMAPASSHADOWMAP = false;
  43293. _this.GAMMALIGHTMAP = false;
  43294. _this.REFLECTION = false;
  43295. _this.REFLECTIONMAP_3D = false;
  43296. _this.REFLECTIONMAP_SPHERICAL = false;
  43297. _this.REFLECTIONMAP_PLANAR = false;
  43298. _this.REFLECTIONMAP_CUBIC = false;
  43299. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43300. _this.REFLECTIONMAP_PROJECTION = false;
  43301. _this.REFLECTIONMAP_SKYBOX = false;
  43302. _this.REFLECTIONMAP_EXPLICIT = false;
  43303. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43304. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43305. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43306. _this.INVERTCUBICMAP = false;
  43307. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43308. _this.USESPHERICALINVERTEX = false;
  43309. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43310. _this.LODINREFLECTIONALPHA = false;
  43311. _this.GAMMAREFLECTION = false;
  43312. _this.RGBDREFLECTION = false;
  43313. _this.RADIANCEOCCLUSION = false;
  43314. _this.HORIZONOCCLUSION = false;
  43315. _this.REFRACTION = false;
  43316. _this.REFRACTIONMAP_3D = false;
  43317. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43318. _this.LODINREFRACTIONALPHA = false;
  43319. _this.GAMMAREFRACTION = false;
  43320. _this.RGBDREFRACTION = false;
  43321. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43322. _this.INSTANCES = false;
  43323. _this.NUM_BONE_INFLUENCERS = 0;
  43324. _this.BonesPerMesh = 0;
  43325. _this.NONUNIFORMSCALING = false;
  43326. _this.MORPHTARGETS = false;
  43327. _this.MORPHTARGETS_NORMAL = false;
  43328. _this.MORPHTARGETS_TANGENT = false;
  43329. _this.NUM_MORPH_INFLUENCERS = 0;
  43330. _this.IMAGEPROCESSING = false;
  43331. _this.VIGNETTE = false;
  43332. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43333. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43334. _this.TONEMAPPING = false;
  43335. _this.CONTRAST = false;
  43336. _this.COLORCURVES = false;
  43337. _this.COLORGRADING = false;
  43338. _this.COLORGRADING3D = false;
  43339. _this.SAMPLER3DGREENDEPTH = false;
  43340. _this.SAMPLER3DBGRMAP = false;
  43341. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43342. _this.EXPOSURE = false;
  43343. _this.USEPHYSICALLIGHTFALLOFF = false;
  43344. _this.TWOSIDEDLIGHTING = false;
  43345. _this.SHADOWFLOAT = false;
  43346. _this.CLIPPLANE = false;
  43347. _this.POINTSIZE = false;
  43348. _this.FOG = false;
  43349. _this.LOGARITHMICDEPTH = false;
  43350. _this.FORCENORMALFORWARD = false;
  43351. _this.SPECULARAA = false;
  43352. _this.UNLIT = false;
  43353. _this.rebuild();
  43354. return _this;
  43355. }
  43356. /**
  43357. * Resets the PBR Material defines.
  43358. */
  43359. PBRMaterialDefines.prototype.reset = function () {
  43360. _super.prototype.reset.call(this);
  43361. this.ALPHATESTVALUE = "0.5";
  43362. this.PBR = true;
  43363. };
  43364. return PBRMaterialDefines;
  43365. }(BABYLON.MaterialDefines));
  43366. /**
  43367. * The Physically based material base class of BJS.
  43368. *
  43369. * This offers the main features of a standard PBR material.
  43370. * For more information, please refer to the documentation :
  43371. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43372. */
  43373. var PBRBaseMaterial = /** @class */ (function (_super) {
  43374. __extends(PBRBaseMaterial, _super);
  43375. /**
  43376. * Instantiates a new PBRMaterial instance.
  43377. *
  43378. * @param name The material name
  43379. * @param scene The scene the material will be use in.
  43380. */
  43381. function PBRBaseMaterial(name, scene) {
  43382. var _this = _super.call(this, name, scene) || this;
  43383. /**
  43384. * Intensity of the direct lights e.g. the four lights available in your scene.
  43385. * This impacts both the direct diffuse and specular highlights.
  43386. */
  43387. _this._directIntensity = 1.0;
  43388. /**
  43389. * Intensity of the emissive part of the material.
  43390. * This helps controlling the emissive effect without modifying the emissive color.
  43391. */
  43392. _this._emissiveIntensity = 1.0;
  43393. /**
  43394. * Intensity of the environment e.g. how much the environment will light the object
  43395. * either through harmonics for rough material or through the refelction for shiny ones.
  43396. */
  43397. _this._environmentIntensity = 1.0;
  43398. /**
  43399. * This is a special control allowing the reduction of the specular highlights coming from the
  43400. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43401. */
  43402. _this._specularIntensity = 1.0;
  43403. /**
  43404. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43405. */
  43406. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43407. /**
  43408. * Debug Control allowing disabling the bump map on this material.
  43409. */
  43410. _this._disableBumpMap = false;
  43411. /**
  43412. * AKA Occlusion Texture Intensity in other nomenclature.
  43413. */
  43414. _this._ambientTextureStrength = 1.0;
  43415. /**
  43416. * The color of a material in ambient lighting.
  43417. */
  43418. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43419. /**
  43420. * AKA Diffuse Color in other nomenclature.
  43421. */
  43422. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43423. /**
  43424. * AKA Specular Color in other nomenclature.
  43425. */
  43426. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43427. /**
  43428. * The color applied when light is reflected from a material.
  43429. */
  43430. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43431. /**
  43432. * The color applied when light is emitted from a material.
  43433. */
  43434. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43435. /**
  43436. * AKA Glossiness in other nomenclature.
  43437. */
  43438. _this._microSurface = 0.9;
  43439. /**
  43440. * source material index of refraction (IOR)' / 'destination material IOR.
  43441. */
  43442. _this._indexOfRefraction = 0.66;
  43443. /**
  43444. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43445. */
  43446. _this._invertRefractionY = false;
  43447. /**
  43448. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43449. * Materials half opaque for instance using refraction could benefit from this control.
  43450. */
  43451. _this._linkRefractionWithTransparency = false;
  43452. /**
  43453. * Specifies that the material will use the light map as a show map.
  43454. */
  43455. _this._useLightmapAsShadowmap = false;
  43456. /**
  43457. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43458. * makes the reflect vector face the model (under horizon).
  43459. */
  43460. _this._useHorizonOcclusion = true;
  43461. /**
  43462. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43463. * too much the area relying on ambient texture to define their ambient occlusion.
  43464. */
  43465. _this._useRadianceOcclusion = true;
  43466. /**
  43467. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43468. */
  43469. _this._useAlphaFromAlbedoTexture = false;
  43470. /**
  43471. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43472. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43473. */
  43474. _this._useSpecularOverAlpha = true;
  43475. /**
  43476. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43477. */
  43478. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43479. /**
  43480. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43481. */
  43482. _this._useRoughnessFromMetallicTextureAlpha = true;
  43483. /**
  43484. * Specifies if the metallic texture contains the roughness information in its green channel.
  43485. */
  43486. _this._useRoughnessFromMetallicTextureGreen = false;
  43487. /**
  43488. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43489. */
  43490. _this._useMetallnessFromMetallicTextureBlue = false;
  43491. /**
  43492. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43493. */
  43494. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43495. /**
  43496. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43497. */
  43498. _this._useAmbientInGrayScale = false;
  43499. /**
  43500. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43501. * The material will try to infer what glossiness each pixel should be.
  43502. */
  43503. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43504. /**
  43505. * BJS is using an harcoded light falloff based on a manually sets up range.
  43506. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43507. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43508. */
  43509. _this._usePhysicalLightFalloff = true;
  43510. /**
  43511. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43512. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43513. */
  43514. _this._useRadianceOverAlpha = true;
  43515. /**
  43516. * Allows using an object space normal map (instead of tangent space).
  43517. */
  43518. _this._useObjectSpaceNormalMap = false;
  43519. /**
  43520. * Allows using the bump map in parallax mode.
  43521. */
  43522. _this._useParallax = false;
  43523. /**
  43524. * Allows using the bump map in parallax occlusion mode.
  43525. */
  43526. _this._useParallaxOcclusion = false;
  43527. /**
  43528. * Controls the scale bias of the parallax mode.
  43529. */
  43530. _this._parallaxScaleBias = 0.05;
  43531. /**
  43532. * If sets to true, disables all the lights affecting the material.
  43533. */
  43534. _this._disableLighting = false;
  43535. /**
  43536. * Number of Simultaneous lights allowed on the material.
  43537. */
  43538. _this._maxSimultaneousLights = 4;
  43539. /**
  43540. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43541. */
  43542. _this._invertNormalMapX = false;
  43543. /**
  43544. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43545. */
  43546. _this._invertNormalMapY = false;
  43547. /**
  43548. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43549. */
  43550. _this._twoSidedLighting = false;
  43551. /**
  43552. * Defines the alpha limits in alpha test mode.
  43553. */
  43554. _this._alphaCutOff = 0.4;
  43555. /**
  43556. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43557. */
  43558. _this._forceAlphaTest = false;
  43559. /**
  43560. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43561. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43562. */
  43563. _this._useAlphaFresnel = false;
  43564. /**
  43565. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43566. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43567. */
  43568. _this._useLinearAlphaFresnel = false;
  43569. /**
  43570. * The transparency mode of the material.
  43571. */
  43572. _this._transparencyMode = null;
  43573. /**
  43574. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43575. * from cos thetav and roughness:
  43576. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43577. */
  43578. _this._environmentBRDFTexture = null;
  43579. /**
  43580. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43581. */
  43582. _this._forceIrradianceInFragment = false;
  43583. /**
  43584. * Force normal to face away from face.
  43585. */
  43586. _this._forceNormalForward = false;
  43587. /**
  43588. * Enables specular anti aliasing in the PBR shader.
  43589. * It will both interacts on the Geometry for analytical and IBL lighting.
  43590. * It also prefilter the roughness map based on the bump values.
  43591. */
  43592. _this._enableSpecularAntiAliasing = false;
  43593. /**
  43594. * Stores the available render targets.
  43595. */
  43596. _this._renderTargets = new BABYLON.SmartArray(16);
  43597. /**
  43598. * Sets the global ambient color for the material used in lighting calculations.
  43599. */
  43600. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43601. /**
  43602. * If set to true, no lighting calculations will be applied.
  43603. */
  43604. _this._unlit = false;
  43605. // Setup the default processing configuration to the scene.
  43606. _this._attachImageProcessingConfiguration(null);
  43607. _this.getRenderTargetTextures = function () {
  43608. _this._renderTargets.reset();
  43609. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43610. _this._renderTargets.push(_this._reflectionTexture);
  43611. }
  43612. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43613. _this._renderTargets.push(_this._refractionTexture);
  43614. }
  43615. return _this._renderTargets;
  43616. };
  43617. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43618. return _this;
  43619. }
  43620. /**
  43621. * Attaches a new image processing configuration to the PBR Material.
  43622. * @param configuration
  43623. */
  43624. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43625. var _this = this;
  43626. if (configuration === this._imageProcessingConfiguration) {
  43627. return;
  43628. }
  43629. // Detaches observer.
  43630. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43631. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43632. }
  43633. // Pick the scene configuration if needed.
  43634. if (!configuration) {
  43635. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43636. }
  43637. else {
  43638. this._imageProcessingConfiguration = configuration;
  43639. }
  43640. // Attaches observer.
  43641. if (this._imageProcessingConfiguration) {
  43642. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43643. _this._markAllSubMeshesAsImageProcessingDirty();
  43644. });
  43645. }
  43646. };
  43647. /**
  43648. * Gets the name of the material class.
  43649. */
  43650. PBRBaseMaterial.prototype.getClassName = function () {
  43651. return "PBRBaseMaterial";
  43652. };
  43653. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43654. /**
  43655. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43656. */
  43657. get: function () {
  43658. return this._useLogarithmicDepth;
  43659. },
  43660. /**
  43661. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43662. */
  43663. set: function (value) {
  43664. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43665. },
  43666. enumerable: true,
  43667. configurable: true
  43668. });
  43669. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43670. /**
  43671. * Gets the current transparency mode.
  43672. */
  43673. get: function () {
  43674. return this._transparencyMode;
  43675. },
  43676. /**
  43677. * Sets the transparency mode of the material.
  43678. *
  43679. * | Value | Type | Description |
  43680. * | ----- | ----------------------------------- | ----------- |
  43681. * | 0 | OPAQUE | |
  43682. * | 1 | ALPHATEST | |
  43683. * | 2 | ALPHABLEND | |
  43684. * | 3 | ALPHATESTANDBLEND | |
  43685. *
  43686. */
  43687. set: function (value) {
  43688. if (this._transparencyMode === value) {
  43689. return;
  43690. }
  43691. this._transparencyMode = value;
  43692. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43693. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43694. },
  43695. enumerable: true,
  43696. configurable: true
  43697. });
  43698. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43699. /**
  43700. * Returns true if alpha blending should be disabled.
  43701. */
  43702. get: function () {
  43703. return (this._linkRefractionWithTransparency ||
  43704. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43705. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43706. },
  43707. enumerable: true,
  43708. configurable: true
  43709. });
  43710. /**
  43711. * Specifies whether or not this material should be rendered in alpha blend mode.
  43712. */
  43713. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43714. if (this._disableAlphaBlending) {
  43715. return false;
  43716. }
  43717. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43718. };
  43719. /**
  43720. * Specifies if the mesh will require alpha blending.
  43721. * @param mesh - BJS mesh.
  43722. */
  43723. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43724. if (this._disableAlphaBlending) {
  43725. return false;
  43726. }
  43727. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43728. };
  43729. /**
  43730. * Specifies whether or not this material should be rendered in alpha test mode.
  43731. */
  43732. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43733. if (this._forceAlphaTest) {
  43734. return true;
  43735. }
  43736. if (this._linkRefractionWithTransparency) {
  43737. return false;
  43738. }
  43739. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43740. };
  43741. /**
  43742. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43743. */
  43744. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43745. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43746. };
  43747. /**
  43748. * Gets the texture used for the alpha test.
  43749. */
  43750. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43751. return this._albedoTexture;
  43752. };
  43753. /**
  43754. * Specifies that the submesh is ready to be used.
  43755. * @param mesh - BJS mesh.
  43756. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43757. * @param useInstances - Specifies that instances should be used.
  43758. * @returns - boolean indicating that the submesh is ready or not.
  43759. */
  43760. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43761. if (subMesh.effect && this.isFrozen) {
  43762. if (this._wasPreviouslyReady) {
  43763. return true;
  43764. }
  43765. }
  43766. if (!subMesh._materialDefines) {
  43767. subMesh._materialDefines = new PBRMaterialDefines();
  43768. }
  43769. var defines = subMesh._materialDefines;
  43770. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43771. if (defines._renderId === this.getScene().getRenderId()) {
  43772. return true;
  43773. }
  43774. }
  43775. var scene = this.getScene();
  43776. var engine = scene.getEngine();
  43777. if (defines._areTexturesDirty) {
  43778. if (scene.texturesEnabled) {
  43779. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43780. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43781. return false;
  43782. }
  43783. }
  43784. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43785. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43786. return false;
  43787. }
  43788. }
  43789. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43790. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43791. return false;
  43792. }
  43793. }
  43794. var reflectionTexture = this._getReflectionTexture();
  43795. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43796. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43797. return false;
  43798. }
  43799. }
  43800. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43801. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43802. return false;
  43803. }
  43804. }
  43805. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43806. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43807. return false;
  43808. }
  43809. }
  43810. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43811. if (this._metallicTexture) {
  43812. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43813. return false;
  43814. }
  43815. }
  43816. else if (this._reflectivityTexture) {
  43817. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43818. return false;
  43819. }
  43820. }
  43821. if (this._microSurfaceTexture) {
  43822. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43823. return false;
  43824. }
  43825. }
  43826. }
  43827. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43828. // Bump texture cannot be not blocking.
  43829. if (!this._bumpTexture.isReady()) {
  43830. return false;
  43831. }
  43832. }
  43833. var refractionTexture = this._getRefractionTexture();
  43834. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43835. if (!refractionTexture.isReadyOrNotBlocking()) {
  43836. return false;
  43837. }
  43838. }
  43839. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43840. // This is blocking.
  43841. if (!this._environmentBRDFTexture.isReady()) {
  43842. return false;
  43843. }
  43844. }
  43845. }
  43846. }
  43847. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43848. if (!this._imageProcessingConfiguration.isReady()) {
  43849. return false;
  43850. }
  43851. }
  43852. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43853. mesh.createNormals(true);
  43854. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43855. }
  43856. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43857. if (effect) {
  43858. scene.resetCachedMaterial();
  43859. subMesh.setEffect(effect, defines);
  43860. this.buildUniformLayout();
  43861. }
  43862. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43863. return false;
  43864. }
  43865. defines._renderId = scene.getRenderId();
  43866. this._wasPreviouslyReady = true;
  43867. return true;
  43868. };
  43869. /**
  43870. * Specifies if the material uses metallic roughness workflow.
  43871. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43872. */
  43873. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43874. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43875. return true;
  43876. }
  43877. return false;
  43878. };
  43879. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43880. if (onCompiled === void 0) { onCompiled = null; }
  43881. if (onError === void 0) { onError = null; }
  43882. if (useInstances === void 0) { useInstances = null; }
  43883. if (useClipPlane === void 0) { useClipPlane = null; }
  43884. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43885. if (!defines.isDirty) {
  43886. return null;
  43887. }
  43888. defines.markAsProcessed();
  43889. var scene = this.getScene();
  43890. var engine = scene.getEngine();
  43891. // Fallbacks
  43892. var fallbacks = new BABYLON.EffectFallbacks();
  43893. var fallbackRank = 0;
  43894. if (defines.USESPHERICALINVERTEX) {
  43895. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43896. }
  43897. if (defines.FOG) {
  43898. fallbacks.addFallback(fallbackRank, "FOG");
  43899. }
  43900. if (defines.SPECULARAA) {
  43901. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43902. }
  43903. if (defines.POINTSIZE) {
  43904. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43905. }
  43906. if (defines.LOGARITHMICDEPTH) {
  43907. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43908. }
  43909. if (defines.PARALLAX) {
  43910. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43911. }
  43912. if (defines.PARALLAXOCCLUSION) {
  43913. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43914. }
  43915. if (defines.ENVIRONMENTBRDF) {
  43916. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43917. }
  43918. if (defines.TANGENT) {
  43919. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43920. }
  43921. if (defines.BUMP) {
  43922. fallbacks.addFallback(fallbackRank++, "BUMP");
  43923. }
  43924. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43925. if (defines.SPECULARTERM) {
  43926. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43927. }
  43928. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43929. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43930. }
  43931. if (defines.LIGHTMAP) {
  43932. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43933. }
  43934. if (defines.NORMAL) {
  43935. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43936. }
  43937. if (defines.AMBIENT) {
  43938. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43939. }
  43940. if (defines.EMISSIVE) {
  43941. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43942. }
  43943. if (defines.VERTEXCOLOR) {
  43944. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43945. }
  43946. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43947. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43948. }
  43949. if (defines.MORPHTARGETS) {
  43950. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43951. }
  43952. //Attributes
  43953. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43954. if (defines.NORMAL) {
  43955. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43956. }
  43957. if (defines.TANGENT) {
  43958. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43959. }
  43960. if (defines.UV1) {
  43961. attribs.push(BABYLON.VertexBuffer.UVKind);
  43962. }
  43963. if (defines.UV2) {
  43964. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43965. }
  43966. if (defines.VERTEXCOLOR) {
  43967. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43968. }
  43969. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43970. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43971. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43972. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43973. "vFogInfos", "vFogColor", "pointSize",
  43974. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43975. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43976. "mBones",
  43977. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43978. "vLightingIntensity",
  43979. "logarithmicDepthConstant",
  43980. "vSphericalX", "vSphericalY", "vSphericalZ",
  43981. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43982. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43983. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43984. "vTangentSpaceParams"
  43985. ];
  43986. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43987. "bumpSampler", "lightmapSampler", "opacitySampler",
  43988. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43989. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43990. "microSurfaceSampler", "environmentBrdfSampler"];
  43991. var uniformBuffers = ["Material", "Scene"];
  43992. if (BABYLON.ImageProcessingConfiguration) {
  43993. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43994. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43995. }
  43996. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43997. uniformsNames: uniforms,
  43998. uniformBuffersNames: uniformBuffers,
  43999. samplers: samplers,
  44000. defines: defines,
  44001. maxSimultaneousLights: this._maxSimultaneousLights
  44002. });
  44003. var join = defines.toString();
  44004. return engine.createEffect("pbr", {
  44005. attributes: attribs,
  44006. uniformsNames: uniforms,
  44007. uniformBuffersNames: uniformBuffers,
  44008. samplers: samplers,
  44009. defines: join,
  44010. fallbacks: fallbacks,
  44011. onCompiled: onCompiled,
  44012. onError: onError,
  44013. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44014. }, engine);
  44015. };
  44016. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44017. if (useInstances === void 0) { useInstances = null; }
  44018. if (useClipPlane === void 0) { useClipPlane = null; }
  44019. var scene = this.getScene();
  44020. var engine = scene.getEngine();
  44021. // Lights
  44022. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44023. defines._needNormals = true;
  44024. // Textures
  44025. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44026. if (defines._areTexturesDirty) {
  44027. defines._needUVs = false;
  44028. if (scene.texturesEnabled) {
  44029. if (scene.getEngine().getCaps().textureLOD) {
  44030. defines.LODBASEDMICROSFURACE = true;
  44031. }
  44032. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44033. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44034. }
  44035. else {
  44036. defines.ALBEDO = false;
  44037. }
  44038. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44039. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44040. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44041. }
  44042. else {
  44043. defines.AMBIENT = false;
  44044. }
  44045. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44046. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44047. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44048. }
  44049. else {
  44050. defines.OPACITY = false;
  44051. }
  44052. var reflectionTexture = this._getReflectionTexture();
  44053. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44054. defines.REFLECTION = true;
  44055. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44056. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44057. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44058. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44059. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44060. defines.INVERTCUBICMAP = true;
  44061. }
  44062. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44063. switch (reflectionTexture.coordinatesMode) {
  44064. case BABYLON.Texture.EXPLICIT_MODE:
  44065. defines.REFLECTIONMAP_EXPLICIT = true;
  44066. break;
  44067. case BABYLON.Texture.PLANAR_MODE:
  44068. defines.REFLECTIONMAP_PLANAR = true;
  44069. break;
  44070. case BABYLON.Texture.PROJECTION_MODE:
  44071. defines.REFLECTIONMAP_PROJECTION = true;
  44072. break;
  44073. case BABYLON.Texture.SKYBOX_MODE:
  44074. defines.REFLECTIONMAP_SKYBOX = true;
  44075. break;
  44076. case BABYLON.Texture.SPHERICAL_MODE:
  44077. defines.REFLECTIONMAP_SPHERICAL = true;
  44078. break;
  44079. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44080. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44081. break;
  44082. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44083. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44084. break;
  44085. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44086. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44087. break;
  44088. case BABYLON.Texture.CUBIC_MODE:
  44089. case BABYLON.Texture.INVCUBIC_MODE:
  44090. default:
  44091. defines.REFLECTIONMAP_CUBIC = true;
  44092. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44093. break;
  44094. }
  44095. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44096. if (reflectionTexture.sphericalPolynomial) {
  44097. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44098. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44099. defines.USESPHERICALINVERTEX = false;
  44100. }
  44101. else {
  44102. defines.USESPHERICALINVERTEX = true;
  44103. }
  44104. }
  44105. }
  44106. }
  44107. else {
  44108. defines.REFLECTION = false;
  44109. defines.REFLECTIONMAP_3D = false;
  44110. defines.REFLECTIONMAP_SPHERICAL = false;
  44111. defines.REFLECTIONMAP_PLANAR = false;
  44112. defines.REFLECTIONMAP_CUBIC = false;
  44113. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44114. defines.REFLECTIONMAP_PROJECTION = false;
  44115. defines.REFLECTIONMAP_SKYBOX = false;
  44116. defines.REFLECTIONMAP_EXPLICIT = false;
  44117. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44118. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44119. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44120. defines.INVERTCUBICMAP = false;
  44121. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44122. defines.USESPHERICALINVERTEX = false;
  44123. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44124. defines.LODINREFLECTIONALPHA = false;
  44125. defines.GAMMAREFLECTION = false;
  44126. defines.RGBDREFLECTION = false;
  44127. }
  44128. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44129. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44130. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44131. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44132. }
  44133. else {
  44134. defines.LIGHTMAP = false;
  44135. }
  44136. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44137. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44138. }
  44139. else {
  44140. defines.EMISSIVE = false;
  44141. }
  44142. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44143. if (this._metallicTexture) {
  44144. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44145. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44146. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44147. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44148. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44149. }
  44150. else if (this._reflectivityTexture) {
  44151. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44152. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44153. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44154. }
  44155. else {
  44156. defines.REFLECTIVITY = false;
  44157. }
  44158. if (this._microSurfaceTexture) {
  44159. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44160. }
  44161. else {
  44162. defines.MICROSURFACEMAP = false;
  44163. }
  44164. }
  44165. else {
  44166. defines.REFLECTIVITY = false;
  44167. defines.MICROSURFACEMAP = false;
  44168. }
  44169. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44170. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44171. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44172. defines.PARALLAX = true;
  44173. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44174. }
  44175. else {
  44176. defines.PARALLAX = false;
  44177. }
  44178. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44179. }
  44180. else {
  44181. defines.BUMP = false;
  44182. }
  44183. var refractionTexture = this._getRefractionTexture();
  44184. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44185. defines.REFRACTION = true;
  44186. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44187. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44188. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44189. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44190. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44191. if (this._linkRefractionWithTransparency) {
  44192. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44193. }
  44194. }
  44195. else {
  44196. defines.REFRACTION = false;
  44197. }
  44198. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44199. defines.ENVIRONMENTBRDF = true;
  44200. }
  44201. else {
  44202. defines.ENVIRONMENTBRDF = false;
  44203. }
  44204. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44205. defines.ALPHAFROMALBEDO = true;
  44206. }
  44207. else {
  44208. defines.ALPHAFROMALBEDO = false;
  44209. }
  44210. }
  44211. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44212. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44213. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44214. if (!this.backFaceCulling && this._twoSidedLighting) {
  44215. defines.TWOSIDEDLIGHTING = true;
  44216. }
  44217. else {
  44218. defines.TWOSIDEDLIGHTING = false;
  44219. }
  44220. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44221. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44222. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44223. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44224. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44225. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44226. }
  44227. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44228. this._imageProcessingConfiguration.prepareDefines(defines);
  44229. }
  44230. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44231. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44232. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44233. // Misc.
  44234. if (defines._areMiscDirty) {
  44235. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44236. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44237. }
  44238. // Values that need to be evaluated on every frame
  44239. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44240. // Attribs
  44241. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44242. };
  44243. /**
  44244. * Force shader compilation
  44245. */
  44246. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44247. var _this = this;
  44248. var localOptions = __assign({ clipPlane: false }, options);
  44249. var defines = new PBRMaterialDefines();
  44250. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44251. if (effect.isReady()) {
  44252. if (onCompiled) {
  44253. onCompiled(this);
  44254. }
  44255. }
  44256. else {
  44257. effect.onCompileObservable.add(function () {
  44258. if (onCompiled) {
  44259. onCompiled(_this);
  44260. }
  44261. });
  44262. }
  44263. };
  44264. /**
  44265. * Initializes the uniform buffer layout for the shader.
  44266. */
  44267. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44268. // Order is important !
  44269. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44270. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44271. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44272. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44273. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44274. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44275. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44276. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44277. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44278. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44279. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44280. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44281. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44282. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44283. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44284. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44285. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44286. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44287. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44288. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44289. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44290. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44291. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44292. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44293. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44294. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44295. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44296. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44297. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44298. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44299. this._uniformBuffer.addUniform("pointSize", 1);
  44300. this._uniformBuffer.create();
  44301. };
  44302. /**
  44303. * Unbinds the textures.
  44304. */
  44305. PBRBaseMaterial.prototype.unbind = function () {
  44306. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44307. this._uniformBuffer.setTexture("reflectionSampler", null);
  44308. }
  44309. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44310. this._uniformBuffer.setTexture("refractionSampler", null);
  44311. }
  44312. _super.prototype.unbind.call(this);
  44313. };
  44314. /**
  44315. * Binds the submesh data.
  44316. * @param world - The world matrix.
  44317. * @param mesh - The BJS mesh.
  44318. * @param subMesh - A submesh of the BJS mesh.
  44319. */
  44320. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44321. var scene = this.getScene();
  44322. var defines = subMesh._materialDefines;
  44323. if (!defines) {
  44324. return;
  44325. }
  44326. var effect = subMesh.effect;
  44327. if (!effect) {
  44328. return;
  44329. }
  44330. this._activeEffect = effect;
  44331. // Matrices
  44332. this.bindOnlyWorldMatrix(world);
  44333. // Normal Matrix
  44334. if (defines.OBJECTSPACE_NORMALMAP) {
  44335. world.toNormalMatrix(this._normalMatrix);
  44336. this.bindOnlyNormalMatrix(this._normalMatrix);
  44337. }
  44338. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44339. // Bones
  44340. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44341. var reflectionTexture = null;
  44342. if (mustRebind) {
  44343. this._uniformBuffer.bindToEffect(effect, "Material");
  44344. this.bindViewProjection(effect);
  44345. reflectionTexture = this._getReflectionTexture();
  44346. var refractionTexture = this._getRefractionTexture();
  44347. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44348. // Texture uniforms
  44349. if (scene.texturesEnabled) {
  44350. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44351. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44352. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44353. }
  44354. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44355. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44356. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44357. }
  44358. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44359. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44360. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44361. }
  44362. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44363. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44364. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44365. if (reflectionTexture.boundingBoxSize) {
  44366. var cubeTexture = reflectionTexture;
  44367. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44368. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44369. }
  44370. var polynomials = reflectionTexture.sphericalPolynomial;
  44371. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44372. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44373. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44374. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44375. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44376. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44377. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44378. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44379. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44380. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44381. }
  44382. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44383. }
  44384. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44385. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44386. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44387. }
  44388. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44389. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44390. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44391. }
  44392. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44393. if (this._metallicTexture) {
  44394. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44395. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44396. }
  44397. else if (this._reflectivityTexture) {
  44398. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44399. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44400. }
  44401. if (this._microSurfaceTexture) {
  44402. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44403. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44404. }
  44405. }
  44406. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44407. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44408. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44409. if (scene._mirroredCameraPosition) {
  44410. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44411. }
  44412. else {
  44413. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44414. }
  44415. }
  44416. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44417. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44418. var depth = 1.0;
  44419. if (!refractionTexture.isCube) {
  44420. if (refractionTexture.depth) {
  44421. depth = refractionTexture.depth;
  44422. }
  44423. }
  44424. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44425. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44426. }
  44427. }
  44428. // Point size
  44429. if (this.pointsCloud) {
  44430. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44431. }
  44432. // Colors
  44433. if (defines.METALLICWORKFLOW) {
  44434. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44435. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44436. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44437. }
  44438. else {
  44439. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44440. }
  44441. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44442. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44443. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44444. // Misc
  44445. this._lightingInfos.x = this._directIntensity;
  44446. this._lightingInfos.y = this._emissiveIntensity;
  44447. this._lightingInfos.z = this._environmentIntensity;
  44448. this._lightingInfos.w = this._specularIntensity;
  44449. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44450. }
  44451. // Textures
  44452. if (scene.texturesEnabled) {
  44453. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44454. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44455. }
  44456. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44457. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44458. }
  44459. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44460. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44461. }
  44462. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44463. if (defines.LODBASEDMICROSFURACE) {
  44464. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44465. }
  44466. else {
  44467. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44468. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44469. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44470. }
  44471. }
  44472. if (defines.ENVIRONMENTBRDF) {
  44473. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44474. }
  44475. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44476. if (defines.LODBASEDMICROSFURACE) {
  44477. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44478. }
  44479. else {
  44480. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44481. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44482. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44483. }
  44484. }
  44485. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44486. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44487. }
  44488. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44489. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44490. }
  44491. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44492. if (this._metallicTexture) {
  44493. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44494. }
  44495. else if (this._reflectivityTexture) {
  44496. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44497. }
  44498. if (this._microSurfaceTexture) {
  44499. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44500. }
  44501. }
  44502. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44503. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44504. }
  44505. }
  44506. // Clip plane
  44507. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44508. // Colors
  44509. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44510. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44511. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44512. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44513. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44514. }
  44515. if (mustRebind || !this.isFrozen) {
  44516. // Lights
  44517. if (scene.lightsEnabled && !this._disableLighting) {
  44518. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44519. }
  44520. // View
  44521. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44522. this.bindView(effect);
  44523. }
  44524. // Fog
  44525. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44526. // Morph targets
  44527. if (defines.NUM_MORPH_INFLUENCERS) {
  44528. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44529. }
  44530. // image processing
  44531. this._imageProcessingConfiguration.bind(this._activeEffect);
  44532. // Log. depth
  44533. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44534. }
  44535. this._uniformBuffer.update();
  44536. this._afterBind(mesh, this._activeEffect);
  44537. };
  44538. /**
  44539. * Returns the animatable textures.
  44540. * @returns - Array of animatable textures.
  44541. */
  44542. PBRBaseMaterial.prototype.getAnimatables = function () {
  44543. var results = [];
  44544. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44545. results.push(this._albedoTexture);
  44546. }
  44547. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44548. results.push(this._ambientTexture);
  44549. }
  44550. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44551. results.push(this._opacityTexture);
  44552. }
  44553. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44554. results.push(this._reflectionTexture);
  44555. }
  44556. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44557. results.push(this._emissiveTexture);
  44558. }
  44559. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44560. results.push(this._metallicTexture);
  44561. }
  44562. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44563. results.push(this._reflectivityTexture);
  44564. }
  44565. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44566. results.push(this._bumpTexture);
  44567. }
  44568. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44569. results.push(this._lightmapTexture);
  44570. }
  44571. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44572. results.push(this._refractionTexture);
  44573. }
  44574. return results;
  44575. };
  44576. /**
  44577. * Returns the texture used for reflections.
  44578. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44579. */
  44580. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44581. if (this._reflectionTexture) {
  44582. return this._reflectionTexture;
  44583. }
  44584. return this.getScene().environmentTexture;
  44585. };
  44586. /**
  44587. * Returns the texture used for refraction or null if none is used.
  44588. * @returns - Refection texture if present. If no refraction texture and refraction
  44589. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44590. */
  44591. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44592. if (this._refractionTexture) {
  44593. return this._refractionTexture;
  44594. }
  44595. if (this._linkRefractionWithTransparency) {
  44596. return this.getScene().environmentTexture;
  44597. }
  44598. return null;
  44599. };
  44600. /**
  44601. * Disposes the resources of the material.
  44602. * @param forceDisposeEffect - Forces the disposal of effects.
  44603. * @param forceDisposeTextures - Forces the disposal of all textures.
  44604. */
  44605. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44606. if (forceDisposeTextures) {
  44607. if (this._albedoTexture) {
  44608. this._albedoTexture.dispose();
  44609. }
  44610. if (this._ambientTexture) {
  44611. this._ambientTexture.dispose();
  44612. }
  44613. if (this._opacityTexture) {
  44614. this._opacityTexture.dispose();
  44615. }
  44616. if (this._reflectionTexture) {
  44617. this._reflectionTexture.dispose();
  44618. }
  44619. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44620. this._environmentBRDFTexture.dispose();
  44621. }
  44622. if (this._emissiveTexture) {
  44623. this._emissiveTexture.dispose();
  44624. }
  44625. if (this._metallicTexture) {
  44626. this._metallicTexture.dispose();
  44627. }
  44628. if (this._reflectivityTexture) {
  44629. this._reflectivityTexture.dispose();
  44630. }
  44631. if (this._bumpTexture) {
  44632. this._bumpTexture.dispose();
  44633. }
  44634. if (this._lightmapTexture) {
  44635. this._lightmapTexture.dispose();
  44636. }
  44637. if (this._refractionTexture) {
  44638. this._refractionTexture.dispose();
  44639. }
  44640. }
  44641. this._renderTargets.dispose();
  44642. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44643. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44644. }
  44645. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44646. };
  44647. /**
  44648. * Stores the reflectivity values based on metallic roughness workflow.
  44649. */
  44650. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44651. __decorate([
  44652. BABYLON.serializeAsImageProcessingConfiguration()
  44653. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44654. __decorate([
  44655. BABYLON.serialize()
  44656. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44657. __decorate([
  44658. BABYLON.serialize()
  44659. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44660. return PBRBaseMaterial;
  44661. }(BABYLON.PushMaterial));
  44662. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44663. })(BABYLON || (BABYLON = {}));
  44664. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44665. var BABYLON;
  44666. (function (BABYLON) {
  44667. /**
  44668. * The Physically based simple base material of BJS.
  44669. *
  44670. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44671. * It is used as the base class for both the specGloss and metalRough conventions.
  44672. */
  44673. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44674. __extends(PBRBaseSimpleMaterial, _super);
  44675. /**
  44676. * Instantiates a new PBRMaterial instance.
  44677. *
  44678. * @param name The material name
  44679. * @param scene The scene the material will be use in.
  44680. */
  44681. function PBRBaseSimpleMaterial(name, scene) {
  44682. var _this = _super.call(this, name, scene) || this;
  44683. /**
  44684. * Number of Simultaneous lights allowed on the material.
  44685. */
  44686. _this.maxSimultaneousLights = 4;
  44687. /**
  44688. * If sets to true, disables all the lights affecting the material.
  44689. */
  44690. _this.disableLighting = false;
  44691. /**
  44692. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44693. */
  44694. _this.invertNormalMapX = false;
  44695. /**
  44696. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44697. */
  44698. _this.invertNormalMapY = false;
  44699. /**
  44700. * Emissivie color used to self-illuminate the model.
  44701. */
  44702. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44703. /**
  44704. * Occlusion Channel Strenght.
  44705. */
  44706. _this.occlusionStrength = 1.0;
  44707. _this.useLightmapAsShadowmap = false;
  44708. _this._useAlphaFromAlbedoTexture = true;
  44709. _this._useAmbientInGrayScale = true;
  44710. return _this;
  44711. }
  44712. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44713. /**
  44714. * Gets the current double sided mode.
  44715. */
  44716. get: function () {
  44717. return this._twoSidedLighting;
  44718. },
  44719. /**
  44720. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44721. */
  44722. set: function (value) {
  44723. if (this._twoSidedLighting === value) {
  44724. return;
  44725. }
  44726. this._twoSidedLighting = value;
  44727. this.backFaceCulling = !value;
  44728. this._markAllSubMeshesAsTexturesDirty();
  44729. },
  44730. enumerable: true,
  44731. configurable: true
  44732. });
  44733. /**
  44734. * Return the active textures of the material.
  44735. */
  44736. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44737. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44738. if (this.environmentTexture) {
  44739. activeTextures.push(this.environmentTexture);
  44740. }
  44741. if (this.normalTexture) {
  44742. activeTextures.push(this.normalTexture);
  44743. }
  44744. if (this.emissiveTexture) {
  44745. activeTextures.push(this.emissiveTexture);
  44746. }
  44747. if (this.occlusionTexture) {
  44748. activeTextures.push(this.occlusionTexture);
  44749. }
  44750. if (this.lightmapTexture) {
  44751. activeTextures.push(this.lightmapTexture);
  44752. }
  44753. return activeTextures;
  44754. };
  44755. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44756. if (_super.prototype.hasTexture.call(this, texture)) {
  44757. return true;
  44758. }
  44759. if (this.lightmapTexture === texture) {
  44760. return true;
  44761. }
  44762. return false;
  44763. };
  44764. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44765. return "PBRBaseSimpleMaterial";
  44766. };
  44767. __decorate([
  44768. BABYLON.serialize(),
  44769. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44770. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44771. __decorate([
  44772. BABYLON.serialize(),
  44773. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44774. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44775. __decorate([
  44776. BABYLON.serializeAsTexture(),
  44777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44778. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44779. __decorate([
  44780. BABYLON.serialize(),
  44781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44782. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44783. __decorate([
  44784. BABYLON.serialize(),
  44785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44786. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44787. __decorate([
  44788. BABYLON.serializeAsTexture(),
  44789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44790. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44791. __decorate([
  44792. BABYLON.serializeAsColor3("emissive"),
  44793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44794. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44795. __decorate([
  44796. BABYLON.serializeAsTexture(),
  44797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44798. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44799. __decorate([
  44800. BABYLON.serialize(),
  44801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44802. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44803. __decorate([
  44804. BABYLON.serializeAsTexture(),
  44805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44806. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44807. __decorate([
  44808. BABYLON.serialize(),
  44809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44810. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44811. __decorate([
  44812. BABYLON.serialize()
  44813. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44814. __decorate([
  44815. BABYLON.serializeAsTexture(),
  44816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44817. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44818. __decorate([
  44819. BABYLON.serialize(),
  44820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44821. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44822. return PBRBaseSimpleMaterial;
  44823. }(BABYLON.PBRBaseMaterial));
  44824. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44825. })(BABYLON || (BABYLON = {}));
  44826. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44827. var BABYLON;
  44828. (function (BABYLON) {
  44829. /**
  44830. * The Physically based material of BJS.
  44831. *
  44832. * This offers the main features of a standard PBR material.
  44833. * For more information, please refer to the documentation :
  44834. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44835. */
  44836. var PBRMaterial = /** @class */ (function (_super) {
  44837. __extends(PBRMaterial, _super);
  44838. /**
  44839. * Instantiates a new PBRMaterial instance.
  44840. *
  44841. * @param name The material name
  44842. * @param scene The scene the material will be use in.
  44843. */
  44844. function PBRMaterial(name, scene) {
  44845. var _this = _super.call(this, name, scene) || this;
  44846. /**
  44847. * Intensity of the direct lights e.g. the four lights available in your scene.
  44848. * This impacts both the direct diffuse and specular highlights.
  44849. */
  44850. _this.directIntensity = 1.0;
  44851. /**
  44852. * Intensity of the emissive part of the material.
  44853. * This helps controlling the emissive effect without modifying the emissive color.
  44854. */
  44855. _this.emissiveIntensity = 1.0;
  44856. /**
  44857. * Intensity of the environment e.g. how much the environment will light the object
  44858. * either through harmonics for rough material or through the refelction for shiny ones.
  44859. */
  44860. _this.environmentIntensity = 1.0;
  44861. /**
  44862. * This is a special control allowing the reduction of the specular highlights coming from the
  44863. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44864. */
  44865. _this.specularIntensity = 1.0;
  44866. /**
  44867. * Debug Control allowing disabling the bump map on this material.
  44868. */
  44869. _this.disableBumpMap = false;
  44870. /**
  44871. * AKA Occlusion Texture Intensity in other nomenclature.
  44872. */
  44873. _this.ambientTextureStrength = 1.0;
  44874. /**
  44875. * The color of a material in ambient lighting.
  44876. */
  44877. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44878. /**
  44879. * AKA Diffuse Color in other nomenclature.
  44880. */
  44881. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44882. /**
  44883. * AKA Specular Color in other nomenclature.
  44884. */
  44885. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44886. /**
  44887. * The color reflected from the material.
  44888. */
  44889. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44890. /**
  44891. * The color emitted from the material.
  44892. */
  44893. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44894. /**
  44895. * AKA Glossiness in other nomenclature.
  44896. */
  44897. _this.microSurface = 1.0;
  44898. /**
  44899. * source material index of refraction (IOR)' / 'destination material IOR.
  44900. */
  44901. _this.indexOfRefraction = 0.66;
  44902. /**
  44903. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44904. */
  44905. _this.invertRefractionY = false;
  44906. /**
  44907. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44908. * Materials half opaque for instance using refraction could benefit from this control.
  44909. */
  44910. _this.linkRefractionWithTransparency = false;
  44911. _this.useLightmapAsShadowmap = false;
  44912. /**
  44913. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44914. */
  44915. _this.useAlphaFromAlbedoTexture = false;
  44916. /**
  44917. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44918. */
  44919. _this.forceAlphaTest = false;
  44920. /**
  44921. * Defines the alpha limits in alpha test mode.
  44922. */
  44923. _this.alphaCutOff = 0.4;
  44924. /**
  44925. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44926. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44927. */
  44928. _this.useSpecularOverAlpha = true;
  44929. /**
  44930. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44931. */
  44932. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44933. /**
  44934. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44935. */
  44936. _this.useRoughnessFromMetallicTextureAlpha = true;
  44937. /**
  44938. * Specifies if the metallic texture contains the roughness information in its green channel.
  44939. */
  44940. _this.useRoughnessFromMetallicTextureGreen = false;
  44941. /**
  44942. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44943. */
  44944. _this.useMetallnessFromMetallicTextureBlue = false;
  44945. /**
  44946. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44947. */
  44948. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44949. /**
  44950. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44951. */
  44952. _this.useAmbientInGrayScale = false;
  44953. /**
  44954. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44955. * The material will try to infer what glossiness each pixel should be.
  44956. */
  44957. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44958. /**
  44959. * BJS is using an harcoded light falloff based on a manually sets up range.
  44960. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44961. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44962. */
  44963. _this.usePhysicalLightFalloff = true;
  44964. /**
  44965. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44966. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44967. */
  44968. _this.useRadianceOverAlpha = true;
  44969. /**
  44970. * Allows using an object space normal map (instead of tangent space).
  44971. */
  44972. _this.useObjectSpaceNormalMap = false;
  44973. /**
  44974. * Allows using the bump map in parallax mode.
  44975. */
  44976. _this.useParallax = false;
  44977. /**
  44978. * Allows using the bump map in parallax occlusion mode.
  44979. */
  44980. _this.useParallaxOcclusion = false;
  44981. /**
  44982. * Controls the scale bias of the parallax mode.
  44983. */
  44984. _this.parallaxScaleBias = 0.05;
  44985. /**
  44986. * If sets to true, disables all the lights affecting the material.
  44987. */
  44988. _this.disableLighting = false;
  44989. /**
  44990. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44991. */
  44992. _this.forceIrradianceInFragment = false;
  44993. /**
  44994. * Number of Simultaneous lights allowed on the material.
  44995. */
  44996. _this.maxSimultaneousLights = 4;
  44997. /**
  44998. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44999. */
  45000. _this.invertNormalMapX = false;
  45001. /**
  45002. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45003. */
  45004. _this.invertNormalMapY = false;
  45005. /**
  45006. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45007. */
  45008. _this.twoSidedLighting = false;
  45009. /**
  45010. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45011. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45012. */
  45013. _this.useAlphaFresnel = false;
  45014. /**
  45015. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45016. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45017. */
  45018. _this.useLinearAlphaFresnel = false;
  45019. /**
  45020. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45021. * And/Or occlude the blended part.
  45022. */
  45023. _this.environmentBRDFTexture = null;
  45024. /**
  45025. * Force normal to face away from face.
  45026. */
  45027. _this.forceNormalForward = false;
  45028. /**
  45029. * Enables specular anti aliasing in the PBR shader.
  45030. * It will both interacts on the Geometry for analytical and IBL lighting.
  45031. * It also prefilter the roughness map based on the bump values.
  45032. */
  45033. _this.enableSpecularAntiAliasing = false;
  45034. /**
  45035. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45036. * makes the reflect vector face the model (under horizon).
  45037. */
  45038. _this.useHorizonOcclusion = true;
  45039. /**
  45040. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45041. * too much the area relying on ambient texture to define their ambient occlusion.
  45042. */
  45043. _this.useRadianceOcclusion = true;
  45044. /**
  45045. * If set to true, no lighting calculations will be applied.
  45046. */
  45047. _this.unlit = false;
  45048. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45049. return _this;
  45050. }
  45051. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45052. /**
  45053. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45054. */
  45055. get: function () {
  45056. return this._PBRMATERIAL_OPAQUE;
  45057. },
  45058. enumerable: true,
  45059. configurable: true
  45060. });
  45061. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45062. /**
  45063. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45064. */
  45065. get: function () {
  45066. return this._PBRMATERIAL_ALPHATEST;
  45067. },
  45068. enumerable: true,
  45069. configurable: true
  45070. });
  45071. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45072. /**
  45073. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45074. */
  45075. get: function () {
  45076. return this._PBRMATERIAL_ALPHABLEND;
  45077. },
  45078. enumerable: true,
  45079. configurable: true
  45080. });
  45081. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45082. /**
  45083. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45084. * They are also discarded below the alpha cutoff threshold to improve performances.
  45085. */
  45086. get: function () {
  45087. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45088. },
  45089. enumerable: true,
  45090. configurable: true
  45091. });
  45092. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45093. /**
  45094. * Gets the image processing configuration used either in this material.
  45095. */
  45096. get: function () {
  45097. return this._imageProcessingConfiguration;
  45098. },
  45099. /**
  45100. * Sets the Default image processing configuration used either in the this material.
  45101. *
  45102. * If sets to null, the scene one is in use.
  45103. */
  45104. set: function (value) {
  45105. this._attachImageProcessingConfiguration(value);
  45106. // Ensure the effect will be rebuilt.
  45107. this._markAllSubMeshesAsTexturesDirty();
  45108. },
  45109. enumerable: true,
  45110. configurable: true
  45111. });
  45112. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45113. /**
  45114. * Gets wether the color curves effect is enabled.
  45115. */
  45116. get: function () {
  45117. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45118. },
  45119. /**
  45120. * Sets wether the color curves effect is enabled.
  45121. */
  45122. set: function (value) {
  45123. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45124. },
  45125. enumerable: true,
  45126. configurable: true
  45127. });
  45128. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45129. /**
  45130. * Gets wether the color grading effect is enabled.
  45131. */
  45132. get: function () {
  45133. return this.imageProcessingConfiguration.colorGradingEnabled;
  45134. },
  45135. /**
  45136. * Gets wether the color grading effect is enabled.
  45137. */
  45138. set: function (value) {
  45139. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45140. },
  45141. enumerable: true,
  45142. configurable: true
  45143. });
  45144. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45145. /**
  45146. * Gets wether tonemapping is enabled or not.
  45147. */
  45148. get: function () {
  45149. return this._imageProcessingConfiguration.toneMappingEnabled;
  45150. },
  45151. /**
  45152. * Sets wether tonemapping is enabled or not
  45153. */
  45154. set: function (value) {
  45155. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45156. },
  45157. enumerable: true,
  45158. configurable: true
  45159. });
  45160. ;
  45161. ;
  45162. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45163. /**
  45164. * The camera exposure used on this material.
  45165. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45166. * This corresponds to a photographic exposure.
  45167. */
  45168. get: function () {
  45169. return this._imageProcessingConfiguration.exposure;
  45170. },
  45171. /**
  45172. * The camera exposure used on this material.
  45173. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45174. * This corresponds to a photographic exposure.
  45175. */
  45176. set: function (value) {
  45177. this._imageProcessingConfiguration.exposure = value;
  45178. },
  45179. enumerable: true,
  45180. configurable: true
  45181. });
  45182. ;
  45183. ;
  45184. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45185. /**
  45186. * Gets The camera contrast used on this material.
  45187. */
  45188. get: function () {
  45189. return this._imageProcessingConfiguration.contrast;
  45190. },
  45191. /**
  45192. * Sets The camera contrast used on this material.
  45193. */
  45194. set: function (value) {
  45195. this._imageProcessingConfiguration.contrast = value;
  45196. },
  45197. enumerable: true,
  45198. configurable: true
  45199. });
  45200. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45201. /**
  45202. * Gets the Color Grading 2D Lookup Texture.
  45203. */
  45204. get: function () {
  45205. return this._imageProcessingConfiguration.colorGradingTexture;
  45206. },
  45207. /**
  45208. * Sets the Color Grading 2D Lookup Texture.
  45209. */
  45210. set: function (value) {
  45211. this._imageProcessingConfiguration.colorGradingTexture = value;
  45212. },
  45213. enumerable: true,
  45214. configurable: true
  45215. });
  45216. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45217. /**
  45218. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45219. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45220. * 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;
  45221. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45222. */
  45223. get: function () {
  45224. return this._imageProcessingConfiguration.colorCurves;
  45225. },
  45226. /**
  45227. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45228. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45229. * 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;
  45230. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45231. */
  45232. set: function (value) {
  45233. this._imageProcessingConfiguration.colorCurves = value;
  45234. },
  45235. enumerable: true,
  45236. configurable: true
  45237. });
  45238. /**
  45239. * Returns the name of this material class.
  45240. */
  45241. PBRMaterial.prototype.getClassName = function () {
  45242. return "PBRMaterial";
  45243. };
  45244. /**
  45245. * Returns an array of the actively used textures.
  45246. * @returns - Array of BaseTextures
  45247. */
  45248. PBRMaterial.prototype.getActiveTextures = function () {
  45249. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45250. if (this._albedoTexture) {
  45251. activeTextures.push(this._albedoTexture);
  45252. }
  45253. if (this._ambientTexture) {
  45254. activeTextures.push(this._ambientTexture);
  45255. }
  45256. if (this._opacityTexture) {
  45257. activeTextures.push(this._opacityTexture);
  45258. }
  45259. if (this._reflectionTexture) {
  45260. activeTextures.push(this._reflectionTexture);
  45261. }
  45262. if (this._emissiveTexture) {
  45263. activeTextures.push(this._emissiveTexture);
  45264. }
  45265. if (this._reflectivityTexture) {
  45266. activeTextures.push(this._reflectivityTexture);
  45267. }
  45268. if (this._metallicTexture) {
  45269. activeTextures.push(this._metallicTexture);
  45270. }
  45271. if (this._microSurfaceTexture) {
  45272. activeTextures.push(this._microSurfaceTexture);
  45273. }
  45274. if (this._bumpTexture) {
  45275. activeTextures.push(this._bumpTexture);
  45276. }
  45277. if (this._lightmapTexture) {
  45278. activeTextures.push(this._lightmapTexture);
  45279. }
  45280. if (this._refractionTexture) {
  45281. activeTextures.push(this._refractionTexture);
  45282. }
  45283. return activeTextures;
  45284. };
  45285. /**
  45286. * Checks to see if a texture is used in the material.
  45287. * @param texture - Base texture to use.
  45288. * @returns - Boolean specifying if a texture is used in the material.
  45289. */
  45290. PBRMaterial.prototype.hasTexture = function (texture) {
  45291. if (_super.prototype.hasTexture.call(this, texture)) {
  45292. return true;
  45293. }
  45294. if (this._albedoTexture === texture) {
  45295. return true;
  45296. }
  45297. if (this._ambientTexture === texture) {
  45298. return true;
  45299. }
  45300. if (this._opacityTexture === texture) {
  45301. return true;
  45302. }
  45303. if (this._reflectionTexture === texture) {
  45304. return true;
  45305. }
  45306. if (this._reflectivityTexture === texture) {
  45307. return true;
  45308. }
  45309. if (this._metallicTexture === texture) {
  45310. return true;
  45311. }
  45312. if (this._microSurfaceTexture === texture) {
  45313. return true;
  45314. }
  45315. if (this._bumpTexture === texture) {
  45316. return true;
  45317. }
  45318. if (this._lightmapTexture === texture) {
  45319. return true;
  45320. }
  45321. if (this._refractionTexture === texture) {
  45322. return true;
  45323. }
  45324. return false;
  45325. };
  45326. /**
  45327. * Makes a duplicate of the current material.
  45328. * @param name - name to use for the new material.
  45329. */
  45330. PBRMaterial.prototype.clone = function (name) {
  45331. var _this = this;
  45332. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45333. clone.id = name;
  45334. clone.name = name;
  45335. return clone;
  45336. };
  45337. /**
  45338. * Serializes this PBR Material.
  45339. * @returns - An object with the serialized material.
  45340. */
  45341. PBRMaterial.prototype.serialize = function () {
  45342. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45343. serializationObject.customType = "BABYLON.PBRMaterial";
  45344. return serializationObject;
  45345. };
  45346. // Statics
  45347. /**
  45348. * Parses a PBR Material from a serialized object.
  45349. * @param source - Serialized object.
  45350. * @param scene - BJS scene instance.
  45351. * @param rootUrl - url for the scene object
  45352. * @returns - PBRMaterial
  45353. */
  45354. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45355. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45356. };
  45357. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45358. /**
  45359. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45360. */
  45361. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45362. /**
  45363. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45364. */
  45365. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45366. /**
  45367. * 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.
  45368. * They are also discarded below the alpha cutoff threshold to improve performances.
  45369. */
  45370. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45371. __decorate([
  45372. BABYLON.serialize(),
  45373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45374. ], PBRMaterial.prototype, "directIntensity", void 0);
  45375. __decorate([
  45376. BABYLON.serialize(),
  45377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45378. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45379. __decorate([
  45380. BABYLON.serialize(),
  45381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45382. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45383. __decorate([
  45384. BABYLON.serialize(),
  45385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45386. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45387. __decorate([
  45388. BABYLON.serialize(),
  45389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45390. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45391. __decorate([
  45392. BABYLON.serializeAsTexture(),
  45393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45394. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45395. __decorate([
  45396. BABYLON.serializeAsTexture(),
  45397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45398. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45399. __decorate([
  45400. BABYLON.serialize(),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45402. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45403. __decorate([
  45404. BABYLON.serializeAsTexture(),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45406. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45407. __decorate([
  45408. BABYLON.serializeAsTexture(),
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45410. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45411. __decorate([
  45412. BABYLON.serializeAsTexture(),
  45413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45414. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45415. __decorate([
  45416. BABYLON.serializeAsTexture(),
  45417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45418. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45419. __decorate([
  45420. BABYLON.serializeAsTexture(),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45422. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45423. __decorate([
  45424. BABYLON.serialize(),
  45425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45426. ], PBRMaterial.prototype, "metallic", void 0);
  45427. __decorate([
  45428. BABYLON.serialize(),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45430. ], PBRMaterial.prototype, "roughness", void 0);
  45431. __decorate([
  45432. BABYLON.serializeAsTexture(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45434. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45435. __decorate([
  45436. BABYLON.serializeAsTexture(),
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45438. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45439. __decorate([
  45440. BABYLON.serializeAsTexture(),
  45441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45442. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45443. __decorate([
  45444. BABYLON.serializeAsTexture(),
  45445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45446. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45447. __decorate([
  45448. BABYLON.serializeAsColor3("ambient"),
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45450. ], PBRMaterial.prototype, "ambientColor", void 0);
  45451. __decorate([
  45452. BABYLON.serializeAsColor3("albedo"),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMaterial.prototype, "albedoColor", void 0);
  45455. __decorate([
  45456. BABYLON.serializeAsColor3("reflectivity"),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45458. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45459. __decorate([
  45460. BABYLON.serializeAsColor3("reflection"),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45462. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45463. __decorate([
  45464. BABYLON.serializeAsColor3("emissive"),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45467. __decorate([
  45468. BABYLON.serialize(),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45470. ], PBRMaterial.prototype, "microSurface", void 0);
  45471. __decorate([
  45472. BABYLON.serialize(),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45475. __decorate([
  45476. BABYLON.serialize(),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45479. __decorate([
  45480. BABYLON.serialize(),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45483. __decorate([
  45484. BABYLON.serialize(),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45487. __decorate([
  45488. BABYLON.serialize(),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45490. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45491. __decorate([
  45492. BABYLON.serialize(),
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45494. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45495. __decorate([
  45496. BABYLON.serialize(),
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45498. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45499. __decorate([
  45500. BABYLON.serialize(),
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45502. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45503. __decorate([
  45504. BABYLON.serialize(),
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45506. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45507. __decorate([
  45508. BABYLON.serialize(),
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45510. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45511. __decorate([
  45512. BABYLON.serialize(),
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45514. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45515. __decorate([
  45516. BABYLON.serialize(),
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45518. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45519. __decorate([
  45520. BABYLON.serialize(),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45522. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45523. __decorate([
  45524. BABYLON.serialize(),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45526. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45527. __decorate([
  45528. BABYLON.serialize(),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45530. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45531. __decorate([
  45532. BABYLON.serialize(),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45535. __decorate([
  45536. BABYLON.serialize(),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45539. __decorate([
  45540. BABYLON.serialize(),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45542. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45543. __decorate([
  45544. BABYLON.serialize(),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45546. ], PBRMaterial.prototype, "useParallax", void 0);
  45547. __decorate([
  45548. BABYLON.serialize(),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45550. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45551. __decorate([
  45552. BABYLON.serialize(),
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45554. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45555. __decorate([
  45556. BABYLON.serialize(),
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45558. ], PBRMaterial.prototype, "disableLighting", void 0);
  45559. __decorate([
  45560. BABYLON.serialize(),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45562. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45563. __decorate([
  45564. BABYLON.serialize(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45566. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45567. __decorate([
  45568. BABYLON.serialize(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45570. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45571. __decorate([
  45572. BABYLON.serialize(),
  45573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45574. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45575. __decorate([
  45576. BABYLON.serialize(),
  45577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45578. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45579. __decorate([
  45580. BABYLON.serialize(),
  45581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45582. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45583. __decorate([
  45584. BABYLON.serialize(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45586. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45587. __decorate([
  45588. BABYLON.serializeAsTexture(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45594. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45603. __decorate([
  45604. BABYLON.serialize(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45607. __decorate([
  45608. BABYLON.serialize(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45610. ], PBRMaterial.prototype, "unlit", void 0);
  45611. return PBRMaterial;
  45612. }(BABYLON.PBRBaseMaterial));
  45613. BABYLON.PBRMaterial = PBRMaterial;
  45614. })(BABYLON || (BABYLON = {}));
  45615. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45616. var BABYLON;
  45617. (function (BABYLON) {
  45618. /**
  45619. * The PBR material of BJS following the metal roughness convention.
  45620. *
  45621. * This fits to the PBR convention in the GLTF definition:
  45622. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45623. */
  45624. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45625. __extends(PBRMetallicRoughnessMaterial, _super);
  45626. /**
  45627. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45628. *
  45629. * @param name The material name
  45630. * @param scene The scene the material will be use in.
  45631. */
  45632. function PBRMetallicRoughnessMaterial(name, scene) {
  45633. var _this = _super.call(this, name, scene) || this;
  45634. _this._useRoughnessFromMetallicTextureAlpha = false;
  45635. _this._useRoughnessFromMetallicTextureGreen = true;
  45636. _this._useMetallnessFromMetallicTextureBlue = true;
  45637. _this.metallic = 1.0;
  45638. _this.roughness = 1.0;
  45639. return _this;
  45640. }
  45641. /**
  45642. * Return the currrent class name of the material.
  45643. */
  45644. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45645. return "PBRMetallicRoughnessMaterial";
  45646. };
  45647. /**
  45648. * Return the active textures of the material.
  45649. */
  45650. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45651. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45652. if (this.baseTexture) {
  45653. activeTextures.push(this.baseTexture);
  45654. }
  45655. if (this.metallicRoughnessTexture) {
  45656. activeTextures.push(this.metallicRoughnessTexture);
  45657. }
  45658. return activeTextures;
  45659. };
  45660. /**
  45661. * Checks to see if a texture is used in the material.
  45662. * @param texture - Base texture to use.
  45663. * @returns - Boolean specifying if a texture is used in the material.
  45664. */
  45665. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45666. if (_super.prototype.hasTexture.call(this, texture)) {
  45667. return true;
  45668. }
  45669. if (this.baseTexture === texture) {
  45670. return true;
  45671. }
  45672. if (this.metallicRoughnessTexture === texture) {
  45673. return true;
  45674. }
  45675. return false;
  45676. };
  45677. /**
  45678. * Makes a duplicate of the current material.
  45679. * @param name - name to use for the new material.
  45680. */
  45681. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45682. var _this = this;
  45683. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45684. clone.id = name;
  45685. clone.name = name;
  45686. return clone;
  45687. };
  45688. /**
  45689. * Serialize the material to a parsable JSON object.
  45690. */
  45691. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45692. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45693. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45694. return serializationObject;
  45695. };
  45696. /**
  45697. * Parses a JSON object correponding to the serialize function.
  45698. */
  45699. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45700. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45701. };
  45702. __decorate([
  45703. BABYLON.serializeAsColor3(),
  45704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45705. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45706. __decorate([
  45707. BABYLON.serializeAsTexture(),
  45708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45709. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45710. __decorate([
  45711. BABYLON.serialize(),
  45712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45713. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45714. __decorate([
  45715. BABYLON.serialize(),
  45716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45717. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45718. __decorate([
  45719. BABYLON.serializeAsTexture(),
  45720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45721. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45722. return PBRMetallicRoughnessMaterial;
  45723. }(BABYLON.PBRBaseSimpleMaterial));
  45724. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45725. })(BABYLON || (BABYLON = {}));
  45726. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45727. var BABYLON;
  45728. (function (BABYLON) {
  45729. /**
  45730. * The PBR material of BJS following the specular glossiness convention.
  45731. *
  45732. * This fits to the PBR convention in the GLTF definition:
  45733. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45734. */
  45735. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45736. __extends(PBRSpecularGlossinessMaterial, _super);
  45737. /**
  45738. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45739. *
  45740. * @param name The material name
  45741. * @param scene The scene the material will be use in.
  45742. */
  45743. function PBRSpecularGlossinessMaterial(name, scene) {
  45744. var _this = _super.call(this, name, scene) || this;
  45745. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45746. return _this;
  45747. }
  45748. /**
  45749. * Return the currrent class name of the material.
  45750. */
  45751. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45752. return "PBRSpecularGlossinessMaterial";
  45753. };
  45754. /**
  45755. * Return the active textures of the material.
  45756. */
  45757. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45758. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45759. if (this.diffuseTexture) {
  45760. activeTextures.push(this.diffuseTexture);
  45761. }
  45762. if (this.specularGlossinessTexture) {
  45763. activeTextures.push(this.specularGlossinessTexture);
  45764. }
  45765. return activeTextures;
  45766. };
  45767. /**
  45768. * Checks to see if a texture is used in the material.
  45769. * @param texture - Base texture to use.
  45770. * @returns - Boolean specifying if a texture is used in the material.
  45771. */
  45772. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45773. if (_super.prototype.hasTexture.call(this, texture)) {
  45774. return true;
  45775. }
  45776. if (this.diffuseTexture === texture) {
  45777. return true;
  45778. }
  45779. if (this.specularGlossinessTexture === texture) {
  45780. return true;
  45781. }
  45782. return false;
  45783. };
  45784. /**
  45785. * Makes a duplicate of the current material.
  45786. * @param name - name to use for the new material.
  45787. */
  45788. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45789. var _this = this;
  45790. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45791. clone.id = name;
  45792. clone.name = name;
  45793. return clone;
  45794. };
  45795. /**
  45796. * Serialize the material to a parsable JSON object.
  45797. */
  45798. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45799. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45800. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45801. return serializationObject;
  45802. };
  45803. /**
  45804. * Parses a JSON object correponding to the serialize function.
  45805. */
  45806. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45807. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45808. };
  45809. __decorate([
  45810. BABYLON.serializeAsColor3("diffuse"),
  45811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45812. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45813. __decorate([
  45814. BABYLON.serializeAsTexture(),
  45815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45816. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45817. __decorate([
  45818. BABYLON.serializeAsColor3("specular"),
  45819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45820. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45821. __decorate([
  45822. BABYLON.serialize(),
  45823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45824. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45825. __decorate([
  45826. BABYLON.serializeAsTexture(),
  45827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45828. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45829. return PBRSpecularGlossinessMaterial;
  45830. }(BABYLON.PBRBaseSimpleMaterial));
  45831. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45832. })(BABYLON || (BABYLON = {}));
  45833. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45834. var BABYLON;
  45835. (function (BABYLON) {
  45836. BABYLON.CameraInputTypes = {};
  45837. var CameraInputsManager = /** @class */ (function () {
  45838. function CameraInputsManager(camera) {
  45839. this.attached = {};
  45840. this.camera = camera;
  45841. this.checkInputs = function () { };
  45842. }
  45843. /**
  45844. * Add an input method to a camera.
  45845. * builtin inputs example: camera.inputs.addGamepad();
  45846. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45847. * @param input camera input method
  45848. */
  45849. CameraInputsManager.prototype.add = function (input) {
  45850. var type = input.getSimpleName();
  45851. if (this.attached[type]) {
  45852. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45853. return;
  45854. }
  45855. this.attached[type] = input;
  45856. input.camera = this.camera;
  45857. //for checkInputs, we are dynamically creating a function
  45858. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45859. if (input.checkInputs) {
  45860. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45861. }
  45862. if (this.attachedElement) {
  45863. input.attachControl(this.attachedElement);
  45864. }
  45865. };
  45866. /**
  45867. * Remove a specific input method from a camera
  45868. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45869. * @param inputToRemove camera input method
  45870. */
  45871. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45872. for (var cam in this.attached) {
  45873. var input = this.attached[cam];
  45874. if (input === inputToRemove) {
  45875. input.detachControl(this.attachedElement);
  45876. input.camera = null;
  45877. delete this.attached[cam];
  45878. this.rebuildInputCheck();
  45879. }
  45880. }
  45881. };
  45882. CameraInputsManager.prototype.removeByType = function (inputType) {
  45883. for (var cam in this.attached) {
  45884. var input = this.attached[cam];
  45885. if (input.getClassName() === inputType) {
  45886. input.detachControl(this.attachedElement);
  45887. input.camera = null;
  45888. delete this.attached[cam];
  45889. this.rebuildInputCheck();
  45890. }
  45891. }
  45892. };
  45893. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45894. var current = this.checkInputs;
  45895. return function () {
  45896. current();
  45897. fn();
  45898. };
  45899. };
  45900. CameraInputsManager.prototype.attachInput = function (input) {
  45901. if (this.attachedElement) {
  45902. input.attachControl(this.attachedElement, this.noPreventDefault);
  45903. }
  45904. };
  45905. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45906. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45907. if (this.attachedElement) {
  45908. return;
  45909. }
  45910. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45911. this.attachedElement = element;
  45912. this.noPreventDefault = noPreventDefault;
  45913. for (var cam in this.attached) {
  45914. this.attached[cam].attachControl(element, noPreventDefault);
  45915. }
  45916. };
  45917. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45918. if (disconnect === void 0) { disconnect = false; }
  45919. if (this.attachedElement !== element) {
  45920. return;
  45921. }
  45922. for (var cam in this.attached) {
  45923. this.attached[cam].detachControl(element);
  45924. if (disconnect) {
  45925. this.attached[cam].camera = null;
  45926. }
  45927. }
  45928. this.attachedElement = null;
  45929. };
  45930. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45931. this.checkInputs = function () { };
  45932. for (var cam in this.attached) {
  45933. var input = this.attached[cam];
  45934. if (input.checkInputs) {
  45935. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45936. }
  45937. }
  45938. };
  45939. /**
  45940. * Remove all attached input methods from a camera
  45941. */
  45942. CameraInputsManager.prototype.clear = function () {
  45943. if (this.attachedElement) {
  45944. this.detachElement(this.attachedElement, true);
  45945. }
  45946. this.attached = {};
  45947. this.attachedElement = null;
  45948. this.checkInputs = function () { };
  45949. };
  45950. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45951. var inputs = {};
  45952. for (var cam in this.attached) {
  45953. var input = this.attached[cam];
  45954. var res = BABYLON.SerializationHelper.Serialize(input);
  45955. inputs[input.getClassName()] = res;
  45956. }
  45957. serializedCamera.inputsmgr = inputs;
  45958. };
  45959. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45960. var parsedInputs = parsedCamera.inputsmgr;
  45961. if (parsedInputs) {
  45962. this.clear();
  45963. for (var n in parsedInputs) {
  45964. var construct = BABYLON.CameraInputTypes[n];
  45965. if (construct) {
  45966. var parsedinput = parsedInputs[n];
  45967. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45968. this.add(input);
  45969. }
  45970. }
  45971. }
  45972. else {
  45973. //2016-03-08 this part is for managing backward compatibility
  45974. for (var n in this.attached) {
  45975. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45976. if (construct) {
  45977. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45978. this.remove(this.attached[n]);
  45979. this.add(input);
  45980. }
  45981. }
  45982. }
  45983. };
  45984. return CameraInputsManager;
  45985. }());
  45986. BABYLON.CameraInputsManager = CameraInputsManager;
  45987. })(BABYLON || (BABYLON = {}));
  45988. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45989. var BABYLON;
  45990. (function (BABYLON) {
  45991. var TargetCamera = /** @class */ (function (_super) {
  45992. __extends(TargetCamera, _super);
  45993. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45994. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45995. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45996. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45997. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45998. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45999. _this.speed = 2.0;
  46000. _this.noRotationConstraint = false;
  46001. _this.lockedTarget = null;
  46002. _this._currentTarget = BABYLON.Vector3.Zero();
  46003. _this._viewMatrix = BABYLON.Matrix.Zero();
  46004. _this._camMatrix = BABYLON.Matrix.Zero();
  46005. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46006. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46007. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46008. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46009. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46010. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46011. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46012. return _this;
  46013. }
  46014. TargetCamera.prototype.getFrontPosition = function (distance) {
  46015. this.getWorldMatrix();
  46016. var direction = this.getTarget().subtract(this.position);
  46017. direction.normalize();
  46018. direction.scaleInPlace(distance);
  46019. return this.globalPosition.add(direction);
  46020. };
  46021. TargetCamera.prototype._getLockedTargetPosition = function () {
  46022. if (!this.lockedTarget) {
  46023. return null;
  46024. }
  46025. if (this.lockedTarget.absolutePosition) {
  46026. this.lockedTarget.computeWorldMatrix();
  46027. }
  46028. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46029. };
  46030. TargetCamera.prototype.storeState = function () {
  46031. this._storedPosition = this.position.clone();
  46032. this._storedRotation = this.rotation.clone();
  46033. if (this.rotationQuaternion) {
  46034. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46035. }
  46036. return _super.prototype.storeState.call(this);
  46037. };
  46038. /**
  46039. * Restored camera state. You must call storeState() first
  46040. */
  46041. TargetCamera.prototype._restoreStateValues = function () {
  46042. if (!_super.prototype._restoreStateValues.call(this)) {
  46043. return false;
  46044. }
  46045. this.position = this._storedPosition.clone();
  46046. this.rotation = this._storedRotation.clone();
  46047. if (this.rotationQuaternion) {
  46048. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46049. }
  46050. this.cameraDirection.copyFromFloats(0, 0, 0);
  46051. this.cameraRotation.copyFromFloats(0, 0);
  46052. return true;
  46053. };
  46054. // Cache
  46055. TargetCamera.prototype._initCache = function () {
  46056. _super.prototype._initCache.call(this);
  46057. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46058. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46059. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46060. };
  46061. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46062. if (!ignoreParentClass) {
  46063. _super.prototype._updateCache.call(this);
  46064. }
  46065. var lockedTargetPosition = this._getLockedTargetPosition();
  46066. if (!lockedTargetPosition) {
  46067. this._cache.lockedTarget = null;
  46068. }
  46069. else {
  46070. if (!this._cache.lockedTarget) {
  46071. this._cache.lockedTarget = lockedTargetPosition.clone();
  46072. }
  46073. else {
  46074. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46075. }
  46076. }
  46077. this._cache.rotation.copyFrom(this.rotation);
  46078. if (this.rotationQuaternion)
  46079. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46080. };
  46081. // Synchronized
  46082. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46083. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46084. return false;
  46085. }
  46086. var lockedTargetPosition = this._getLockedTargetPosition();
  46087. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46088. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46089. };
  46090. // Methods
  46091. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46092. var engine = this.getEngine();
  46093. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46094. };
  46095. // Target
  46096. TargetCamera.prototype.setTarget = function (target) {
  46097. this.upVector.normalize();
  46098. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46099. this._camMatrix.invert();
  46100. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46101. var vDir = target.subtract(this.position);
  46102. if (vDir.x >= 0.0) {
  46103. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46104. }
  46105. else {
  46106. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46107. }
  46108. this.rotation.z = 0;
  46109. if (isNaN(this.rotation.x)) {
  46110. this.rotation.x = 0;
  46111. }
  46112. if (isNaN(this.rotation.y)) {
  46113. this.rotation.y = 0;
  46114. }
  46115. if (isNaN(this.rotation.z)) {
  46116. this.rotation.z = 0;
  46117. }
  46118. if (this.rotationQuaternion) {
  46119. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46120. }
  46121. };
  46122. /**
  46123. * Return the current target position of the camera. This value is expressed in local space.
  46124. */
  46125. TargetCamera.prototype.getTarget = function () {
  46126. return this._currentTarget;
  46127. };
  46128. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46129. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46130. };
  46131. TargetCamera.prototype._updatePosition = function () {
  46132. if (this.parent) {
  46133. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46134. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46135. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46136. return;
  46137. }
  46138. this.position.addInPlace(this.cameraDirection);
  46139. };
  46140. TargetCamera.prototype._checkInputs = function () {
  46141. var needToMove = this._decideIfNeedsToMove();
  46142. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46143. // Move
  46144. if (needToMove) {
  46145. this._updatePosition();
  46146. }
  46147. // Rotate
  46148. if (needToRotate) {
  46149. this.rotation.x += this.cameraRotation.x;
  46150. this.rotation.y += this.cameraRotation.y;
  46151. //rotate, if quaternion is set and rotation was used
  46152. if (this.rotationQuaternion) {
  46153. var len = this.rotation.lengthSquared();
  46154. if (len) {
  46155. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46156. }
  46157. }
  46158. if (!this.noRotationConstraint) {
  46159. var limit = (Math.PI / 2) * 0.95;
  46160. if (this.rotation.x > limit)
  46161. this.rotation.x = limit;
  46162. if (this.rotation.x < -limit)
  46163. this.rotation.x = -limit;
  46164. }
  46165. }
  46166. // Inertia
  46167. if (needToMove) {
  46168. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46169. this.cameraDirection.x = 0;
  46170. }
  46171. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46172. this.cameraDirection.y = 0;
  46173. }
  46174. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46175. this.cameraDirection.z = 0;
  46176. }
  46177. this.cameraDirection.scaleInPlace(this.inertia);
  46178. }
  46179. if (needToRotate) {
  46180. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46181. this.cameraRotation.x = 0;
  46182. }
  46183. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46184. this.cameraRotation.y = 0;
  46185. }
  46186. this.cameraRotation.scaleInPlace(this.inertia);
  46187. }
  46188. _super.prototype._checkInputs.call(this);
  46189. };
  46190. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46191. if (this.rotationQuaternion) {
  46192. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46193. }
  46194. else {
  46195. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46196. }
  46197. //update the up vector!
  46198. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46199. };
  46200. TargetCamera.prototype._getViewMatrix = function () {
  46201. if (this.lockedTarget) {
  46202. this.setTarget(this._getLockedTargetPosition());
  46203. }
  46204. // Compute
  46205. this._updateCameraRotationMatrix();
  46206. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46207. // Computing target and final matrix
  46208. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46209. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46210. return this._viewMatrix;
  46211. };
  46212. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46213. if (this.parent) {
  46214. var parentWorldMatrix = this.parent.getWorldMatrix();
  46215. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46216. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46217. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46218. this._markSyncedWithParent();
  46219. }
  46220. else {
  46221. this._globalPosition.copyFrom(this.position);
  46222. this._globalCurrentTarget.copyFrom(target);
  46223. this._globalCurrentUpVector.copyFrom(up);
  46224. }
  46225. if (this.getScene().useRightHandedSystem) {
  46226. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46227. }
  46228. else {
  46229. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46230. }
  46231. };
  46232. /**
  46233. * @override
  46234. * Override Camera.createRigCamera
  46235. */
  46236. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46237. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46238. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46239. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46240. if (!this.rotationQuaternion) {
  46241. this.rotationQuaternion = new BABYLON.Quaternion();
  46242. }
  46243. rigCamera._cameraRigParams = {};
  46244. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46245. }
  46246. return rigCamera;
  46247. }
  46248. return null;
  46249. };
  46250. /**
  46251. * @override
  46252. * Override Camera._updateRigCameras
  46253. */
  46254. TargetCamera.prototype._updateRigCameras = function () {
  46255. var camLeft = this._rigCameras[0];
  46256. var camRight = this._rigCameras[1];
  46257. switch (this.cameraRigMode) {
  46258. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46259. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46260. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46261. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46262. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46263. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46264. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46265. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46266. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46267. camLeft.setTarget(this.getTarget());
  46268. camRight.setTarget(this.getTarget());
  46269. break;
  46270. case BABYLON.Camera.RIG_MODE_VR:
  46271. if (camLeft.rotationQuaternion) {
  46272. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46273. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46274. }
  46275. else {
  46276. camLeft.rotation.copyFrom(this.rotation);
  46277. camRight.rotation.copyFrom(this.rotation);
  46278. }
  46279. camLeft.position.copyFrom(this.position);
  46280. camRight.position.copyFrom(this.position);
  46281. break;
  46282. }
  46283. _super.prototype._updateRigCameras.call(this);
  46284. };
  46285. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46286. if (!this._rigCamTransformMatrix) {
  46287. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46288. }
  46289. var target = this.getTarget();
  46290. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46291. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46292. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46293. };
  46294. TargetCamera.prototype.getClassName = function () {
  46295. return "TargetCamera";
  46296. };
  46297. __decorate([
  46298. BABYLON.serializeAsVector3()
  46299. ], TargetCamera.prototype, "rotation", void 0);
  46300. __decorate([
  46301. BABYLON.serialize()
  46302. ], TargetCamera.prototype, "speed", void 0);
  46303. __decorate([
  46304. BABYLON.serializeAsMeshReference("lockedTargetId")
  46305. ], TargetCamera.prototype, "lockedTarget", void 0);
  46306. return TargetCamera;
  46307. }(BABYLON.Camera));
  46308. BABYLON.TargetCamera = TargetCamera;
  46309. })(BABYLON || (BABYLON = {}));
  46310. //# sourceMappingURL=babylon.targetCamera.js.map
  46311. var BABYLON;
  46312. (function (BABYLON) {
  46313. var FreeCameraMouseInput = /** @class */ (function () {
  46314. function FreeCameraMouseInput(touchEnabled) {
  46315. if (touchEnabled === void 0) { touchEnabled = true; }
  46316. this.touchEnabled = touchEnabled;
  46317. this.buttons = [0, 1, 2];
  46318. this.angularSensibility = 2000.0;
  46319. this.previousPosition = null;
  46320. }
  46321. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46322. var _this = this;
  46323. var engine = this.camera.getEngine();
  46324. if (!this._pointerInput) {
  46325. this._pointerInput = function (p, s) {
  46326. var evt = p.event;
  46327. if (engine.isInVRExclusivePointerMode) {
  46328. return;
  46329. }
  46330. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46331. return;
  46332. }
  46333. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46334. return;
  46335. }
  46336. var srcElement = (evt.srcElement || evt.target);
  46337. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46338. try {
  46339. srcElement.setPointerCapture(evt.pointerId);
  46340. }
  46341. catch (e) {
  46342. //Nothing to do with the error. Execution will continue.
  46343. }
  46344. _this.previousPosition = {
  46345. x: evt.clientX,
  46346. y: evt.clientY
  46347. };
  46348. if (!noPreventDefault) {
  46349. evt.preventDefault();
  46350. element.focus();
  46351. }
  46352. }
  46353. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46354. try {
  46355. srcElement.releasePointerCapture(evt.pointerId);
  46356. }
  46357. catch (e) {
  46358. //Nothing to do with the error.
  46359. }
  46360. _this.previousPosition = null;
  46361. if (!noPreventDefault) {
  46362. evt.preventDefault();
  46363. }
  46364. }
  46365. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46366. if (!_this.previousPosition || engine.isPointerLock) {
  46367. return;
  46368. }
  46369. var offsetX = evt.clientX - _this.previousPosition.x;
  46370. if (_this.camera.getScene().useRightHandedSystem)
  46371. offsetX *= -1;
  46372. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46373. offsetX *= -1;
  46374. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46375. var offsetY = evt.clientY - _this.previousPosition.y;
  46376. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46377. _this.previousPosition = {
  46378. x: evt.clientX,
  46379. y: evt.clientY
  46380. };
  46381. if (!noPreventDefault) {
  46382. evt.preventDefault();
  46383. }
  46384. }
  46385. };
  46386. }
  46387. this._onMouseMove = function (evt) {
  46388. if (!engine.isPointerLock) {
  46389. return;
  46390. }
  46391. if (engine.isInVRExclusivePointerMode) {
  46392. return;
  46393. }
  46394. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46395. if (_this.camera.getScene().useRightHandedSystem)
  46396. offsetX *= -1;
  46397. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46398. offsetX *= -1;
  46399. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46400. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46401. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46402. _this.previousPosition = null;
  46403. if (!noPreventDefault) {
  46404. evt.preventDefault();
  46405. }
  46406. };
  46407. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46408. element.addEventListener("mousemove", this._onMouseMove, false);
  46409. };
  46410. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46411. if (this._observer && element) {
  46412. this.camera.getScene().onPointerObservable.remove(this._observer);
  46413. if (this._onMouseMove) {
  46414. element.removeEventListener("mousemove", this._onMouseMove);
  46415. }
  46416. this._observer = null;
  46417. this._onMouseMove = null;
  46418. this.previousPosition = null;
  46419. }
  46420. };
  46421. FreeCameraMouseInput.prototype.getClassName = function () {
  46422. return "FreeCameraMouseInput";
  46423. };
  46424. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46425. return "mouse";
  46426. };
  46427. __decorate([
  46428. BABYLON.serialize()
  46429. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46430. __decorate([
  46431. BABYLON.serialize()
  46432. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46433. return FreeCameraMouseInput;
  46434. }());
  46435. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46436. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46437. })(BABYLON || (BABYLON = {}));
  46438. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46439. var BABYLON;
  46440. (function (BABYLON) {
  46441. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46442. function FreeCameraKeyboardMoveInput() {
  46443. this._keys = new Array();
  46444. this.keysUp = [38];
  46445. this.keysDown = [40];
  46446. this.keysLeft = [37];
  46447. this.keysRight = [39];
  46448. }
  46449. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46450. var _this = this;
  46451. if (this._onCanvasBlurObserver) {
  46452. return;
  46453. }
  46454. this._scene = this.camera.getScene();
  46455. this._engine = this._scene.getEngine();
  46456. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46457. _this._keys = [];
  46458. });
  46459. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46460. var evt = info.event;
  46461. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46462. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46463. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46464. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46465. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46466. var index = _this._keys.indexOf(evt.keyCode);
  46467. if (index === -1) {
  46468. _this._keys.push(evt.keyCode);
  46469. }
  46470. if (!noPreventDefault) {
  46471. evt.preventDefault();
  46472. }
  46473. }
  46474. }
  46475. else {
  46476. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46477. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46478. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46479. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46480. var index = _this._keys.indexOf(evt.keyCode);
  46481. if (index >= 0) {
  46482. _this._keys.splice(index, 1);
  46483. }
  46484. if (!noPreventDefault) {
  46485. evt.preventDefault();
  46486. }
  46487. }
  46488. }
  46489. });
  46490. };
  46491. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46492. if (this._scene) {
  46493. if (this._onKeyboardObserver) {
  46494. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46495. }
  46496. if (this._onCanvasBlurObserver) {
  46497. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46498. }
  46499. this._onKeyboardObserver = null;
  46500. this._onCanvasBlurObserver = null;
  46501. }
  46502. this._keys = [];
  46503. };
  46504. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46505. if (this._onKeyboardObserver) {
  46506. var camera = this.camera;
  46507. // Keyboard
  46508. for (var index = 0; index < this._keys.length; index++) {
  46509. var keyCode = this._keys[index];
  46510. var speed = camera._computeLocalCameraSpeed();
  46511. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46512. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46513. }
  46514. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46515. camera._localDirection.copyFromFloats(0, 0, speed);
  46516. }
  46517. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46518. camera._localDirection.copyFromFloats(speed, 0, 0);
  46519. }
  46520. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46521. camera._localDirection.copyFromFloats(0, 0, -speed);
  46522. }
  46523. if (camera.getScene().useRightHandedSystem) {
  46524. camera._localDirection.z *= -1;
  46525. }
  46526. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46527. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46528. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46529. }
  46530. }
  46531. };
  46532. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46533. return "FreeCameraKeyboardMoveInput";
  46534. };
  46535. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46536. this._keys = [];
  46537. };
  46538. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46539. return "keyboard";
  46540. };
  46541. __decorate([
  46542. BABYLON.serialize()
  46543. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46544. __decorate([
  46545. BABYLON.serialize()
  46546. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46547. __decorate([
  46548. BABYLON.serialize()
  46549. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46550. __decorate([
  46551. BABYLON.serialize()
  46552. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46553. return FreeCameraKeyboardMoveInput;
  46554. }());
  46555. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46556. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46557. })(BABYLON || (BABYLON = {}));
  46558. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46559. var BABYLON;
  46560. (function (BABYLON) {
  46561. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46562. __extends(FreeCameraInputsManager, _super);
  46563. function FreeCameraInputsManager(camera) {
  46564. return _super.call(this, camera) || this;
  46565. }
  46566. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46567. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46568. return this;
  46569. };
  46570. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46571. if (touchEnabled === void 0) { touchEnabled = true; }
  46572. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46573. return this;
  46574. };
  46575. FreeCameraInputsManager.prototype.addGamepad = function () {
  46576. this.add(new BABYLON.FreeCameraGamepadInput());
  46577. return this;
  46578. };
  46579. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46580. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46581. return this;
  46582. };
  46583. FreeCameraInputsManager.prototype.addTouch = function () {
  46584. this.add(new BABYLON.FreeCameraTouchInput());
  46585. return this;
  46586. };
  46587. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46588. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46589. return this;
  46590. };
  46591. return FreeCameraInputsManager;
  46592. }(BABYLON.CameraInputsManager));
  46593. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46594. })(BABYLON || (BABYLON = {}));
  46595. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46596. var BABYLON;
  46597. (function (BABYLON) {
  46598. var FreeCamera = /** @class */ (function (_super) {
  46599. __extends(FreeCamera, _super);
  46600. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46601. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46602. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46603. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46604. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46605. _this.checkCollisions = false;
  46606. _this.applyGravity = false;
  46607. _this._needMoveForGravity = false;
  46608. _this._oldPosition = BABYLON.Vector3.Zero();
  46609. _this._diffPosition = BABYLON.Vector3.Zero();
  46610. _this._newPosition = BABYLON.Vector3.Zero();
  46611. // Collisions
  46612. _this._collisionMask = -1;
  46613. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46614. if (collidedMesh === void 0) { collidedMesh = null; }
  46615. //TODO move this to the collision coordinator!
  46616. if (_this.getScene().workerCollisions)
  46617. newPosition.multiplyInPlace(_this._collider._radius);
  46618. var updatePosition = function (newPos) {
  46619. _this._newPosition.copyFrom(newPos);
  46620. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46621. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46622. _this.position.addInPlace(_this._diffPosition);
  46623. if (_this.onCollide && collidedMesh) {
  46624. _this.onCollide(collidedMesh);
  46625. }
  46626. }
  46627. };
  46628. updatePosition(newPosition);
  46629. };
  46630. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46631. _this.inputs.addKeyboard().addMouse();
  46632. return _this;
  46633. }
  46634. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46635. //-- begin properties for backward compatibility for inputs
  46636. /**
  46637. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46638. * Higher values reduce sensitivity.
  46639. */
  46640. get: function () {
  46641. var mouse = this.inputs.attached["mouse"];
  46642. if (mouse)
  46643. return mouse.angularSensibility;
  46644. return 0;
  46645. },
  46646. /**
  46647. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46648. * Higher values reduce sensitivity.
  46649. */
  46650. set: function (value) {
  46651. var mouse = this.inputs.attached["mouse"];
  46652. if (mouse)
  46653. mouse.angularSensibility = value;
  46654. },
  46655. enumerable: true,
  46656. configurable: true
  46657. });
  46658. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46659. get: function () {
  46660. var keyboard = this.inputs.attached["keyboard"];
  46661. if (keyboard)
  46662. return keyboard.keysUp;
  46663. return [];
  46664. },
  46665. set: function (value) {
  46666. var keyboard = this.inputs.attached["keyboard"];
  46667. if (keyboard)
  46668. keyboard.keysUp = value;
  46669. },
  46670. enumerable: true,
  46671. configurable: true
  46672. });
  46673. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46674. get: function () {
  46675. var keyboard = this.inputs.attached["keyboard"];
  46676. if (keyboard)
  46677. return keyboard.keysDown;
  46678. return [];
  46679. },
  46680. set: function (value) {
  46681. var keyboard = this.inputs.attached["keyboard"];
  46682. if (keyboard)
  46683. keyboard.keysDown = value;
  46684. },
  46685. enumerable: true,
  46686. configurable: true
  46687. });
  46688. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46689. get: function () {
  46690. var keyboard = this.inputs.attached["keyboard"];
  46691. if (keyboard)
  46692. return keyboard.keysLeft;
  46693. return [];
  46694. },
  46695. set: function (value) {
  46696. var keyboard = this.inputs.attached["keyboard"];
  46697. if (keyboard)
  46698. keyboard.keysLeft = value;
  46699. },
  46700. enumerable: true,
  46701. configurable: true
  46702. });
  46703. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46704. get: function () {
  46705. var keyboard = this.inputs.attached["keyboard"];
  46706. if (keyboard)
  46707. return keyboard.keysRight;
  46708. return [];
  46709. },
  46710. set: function (value) {
  46711. var keyboard = this.inputs.attached["keyboard"];
  46712. if (keyboard)
  46713. keyboard.keysRight = value;
  46714. },
  46715. enumerable: true,
  46716. configurable: true
  46717. });
  46718. // Controls
  46719. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46720. this.inputs.attachElement(element, noPreventDefault);
  46721. };
  46722. FreeCamera.prototype.detachControl = function (element) {
  46723. this.inputs.detachElement(element);
  46724. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46725. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46726. };
  46727. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46728. get: function () {
  46729. return this._collisionMask;
  46730. },
  46731. set: function (mask) {
  46732. this._collisionMask = !isNaN(mask) ? mask : -1;
  46733. },
  46734. enumerable: true,
  46735. configurable: true
  46736. });
  46737. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46738. var globalPosition;
  46739. if (this.parent) {
  46740. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46741. }
  46742. else {
  46743. globalPosition = this.position;
  46744. }
  46745. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46746. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46747. if (!this._collider) {
  46748. this._collider = new BABYLON.Collider();
  46749. }
  46750. this._collider._radius = this.ellipsoid;
  46751. this._collider.collisionMask = this._collisionMask;
  46752. //no need for clone, as long as gravity is not on.
  46753. var actualDisplacement = displacement;
  46754. //add gravity to the direction to prevent the dual-collision checking
  46755. if (this.applyGravity) {
  46756. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46757. actualDisplacement = displacement.add(this.getScene().gravity);
  46758. }
  46759. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46760. };
  46761. FreeCamera.prototype._checkInputs = function () {
  46762. if (!this._localDirection) {
  46763. this._localDirection = BABYLON.Vector3.Zero();
  46764. this._transformedDirection = BABYLON.Vector3.Zero();
  46765. }
  46766. this.inputs.checkInputs();
  46767. _super.prototype._checkInputs.call(this);
  46768. };
  46769. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46770. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46771. };
  46772. FreeCamera.prototype._updatePosition = function () {
  46773. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46774. this._collideWithWorld(this.cameraDirection);
  46775. }
  46776. else {
  46777. _super.prototype._updatePosition.call(this);
  46778. }
  46779. };
  46780. FreeCamera.prototype.dispose = function () {
  46781. this.inputs.clear();
  46782. _super.prototype.dispose.call(this);
  46783. };
  46784. FreeCamera.prototype.getClassName = function () {
  46785. return "FreeCamera";
  46786. };
  46787. __decorate([
  46788. BABYLON.serializeAsVector3()
  46789. ], FreeCamera.prototype, "ellipsoid", void 0);
  46790. __decorate([
  46791. BABYLON.serializeAsVector3()
  46792. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46793. __decorate([
  46794. BABYLON.serialize()
  46795. ], FreeCamera.prototype, "checkCollisions", void 0);
  46796. __decorate([
  46797. BABYLON.serialize()
  46798. ], FreeCamera.prototype, "applyGravity", void 0);
  46799. return FreeCamera;
  46800. }(BABYLON.TargetCamera));
  46801. BABYLON.FreeCamera = FreeCamera;
  46802. })(BABYLON || (BABYLON = {}));
  46803. //# sourceMappingURL=babylon.freeCamera.js.map
  46804. var BABYLON;
  46805. (function (BABYLON) {
  46806. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46807. function ArcRotateCameraKeyboardMoveInput() {
  46808. this._keys = new Array();
  46809. this.keysUp = [38];
  46810. this.keysDown = [40];
  46811. this.keysLeft = [37];
  46812. this.keysRight = [39];
  46813. this.keysReset = [220];
  46814. this.panningSensibility = 50.0;
  46815. this.zoomingSensibility = 25.0;
  46816. this.useAltToZoom = true;
  46817. }
  46818. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46819. var _this = this;
  46820. if (this._onCanvasBlurObserver) {
  46821. return;
  46822. }
  46823. this._scene = this.camera.getScene();
  46824. this._engine = this._scene.getEngine();
  46825. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46826. _this._keys = [];
  46827. });
  46828. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46829. var evt = info.event;
  46830. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46831. _this._ctrlPressed = evt.ctrlKey;
  46832. _this._altPressed = evt.altKey;
  46833. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46834. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46835. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46836. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46837. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46838. var index = _this._keys.indexOf(evt.keyCode);
  46839. if (index === -1) {
  46840. _this._keys.push(evt.keyCode);
  46841. }
  46842. if (evt.preventDefault) {
  46843. if (!noPreventDefault) {
  46844. evt.preventDefault();
  46845. }
  46846. }
  46847. }
  46848. }
  46849. else {
  46850. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46851. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46852. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46853. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46854. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46855. var index = _this._keys.indexOf(evt.keyCode);
  46856. if (index >= 0) {
  46857. _this._keys.splice(index, 1);
  46858. }
  46859. if (evt.preventDefault) {
  46860. if (!noPreventDefault) {
  46861. evt.preventDefault();
  46862. }
  46863. }
  46864. }
  46865. }
  46866. });
  46867. };
  46868. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46869. if (this._scene) {
  46870. if (this._onKeyboardObserver) {
  46871. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46872. }
  46873. if (this._onCanvasBlurObserver) {
  46874. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46875. }
  46876. this._onKeyboardObserver = null;
  46877. this._onCanvasBlurObserver = null;
  46878. }
  46879. this._keys = [];
  46880. };
  46881. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46882. if (this._onKeyboardObserver) {
  46883. var camera = this.camera;
  46884. for (var index = 0; index < this._keys.length; index++) {
  46885. var keyCode = this._keys[index];
  46886. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46887. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46888. camera.inertialPanningX -= 1 / this.panningSensibility;
  46889. }
  46890. else {
  46891. camera.inertialAlphaOffset -= 0.01;
  46892. }
  46893. }
  46894. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46895. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46896. camera.inertialPanningY += 1 / this.panningSensibility;
  46897. }
  46898. else if (this._altPressed && this.useAltToZoom) {
  46899. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46900. }
  46901. else {
  46902. camera.inertialBetaOffset -= 0.01;
  46903. }
  46904. }
  46905. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46906. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46907. camera.inertialPanningX += 1 / this.panningSensibility;
  46908. }
  46909. else {
  46910. camera.inertialAlphaOffset += 0.01;
  46911. }
  46912. }
  46913. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46914. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46915. camera.inertialPanningY -= 1 / this.panningSensibility;
  46916. }
  46917. else if (this._altPressed && this.useAltToZoom) {
  46918. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46919. }
  46920. else {
  46921. camera.inertialBetaOffset += 0.01;
  46922. }
  46923. }
  46924. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46925. camera.restoreState();
  46926. }
  46927. }
  46928. }
  46929. };
  46930. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46931. return "ArcRotateCameraKeyboardMoveInput";
  46932. };
  46933. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46934. return "keyboard";
  46935. };
  46936. __decorate([
  46937. BABYLON.serialize()
  46938. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46939. __decorate([
  46940. BABYLON.serialize()
  46941. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46942. __decorate([
  46943. BABYLON.serialize()
  46944. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46945. __decorate([
  46946. BABYLON.serialize()
  46947. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46948. __decorate([
  46949. BABYLON.serialize()
  46950. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46951. __decorate([
  46952. BABYLON.serialize()
  46953. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46954. __decorate([
  46955. BABYLON.serialize()
  46956. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46957. __decorate([
  46958. BABYLON.serialize()
  46959. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46960. return ArcRotateCameraKeyboardMoveInput;
  46961. }());
  46962. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46963. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46964. })(BABYLON || (BABYLON = {}));
  46965. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46966. var BABYLON;
  46967. (function (BABYLON) {
  46968. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46969. function ArcRotateCameraMouseWheelInput() {
  46970. this.wheelPrecision = 3.0;
  46971. /**
  46972. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46973. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46974. */
  46975. this.wheelDeltaPercentage = 0;
  46976. }
  46977. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46978. var _this = this;
  46979. this._wheel = function (p, s) {
  46980. //sanity check - this should be a PointerWheel event.
  46981. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46982. return;
  46983. var event = p.event;
  46984. var delta = 0;
  46985. if (event.wheelDelta) {
  46986. if (_this.wheelDeltaPercentage) {
  46987. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46988. if (event.wheelDelta > 0) {
  46989. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46990. }
  46991. else {
  46992. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46993. }
  46994. }
  46995. else {
  46996. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46997. }
  46998. }
  46999. else if (event.detail) {
  47000. delta = -event.detail / _this.wheelPrecision;
  47001. }
  47002. if (delta)
  47003. _this.camera.inertialRadiusOffset += delta;
  47004. if (event.preventDefault) {
  47005. if (!noPreventDefault) {
  47006. event.preventDefault();
  47007. }
  47008. }
  47009. };
  47010. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47011. };
  47012. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47013. if (this._observer && element) {
  47014. this.camera.getScene().onPointerObservable.remove(this._observer);
  47015. this._observer = null;
  47016. this._wheel = null;
  47017. }
  47018. };
  47019. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47020. return "ArcRotateCameraMouseWheelInput";
  47021. };
  47022. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47023. return "mousewheel";
  47024. };
  47025. __decorate([
  47026. BABYLON.serialize()
  47027. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47028. __decorate([
  47029. BABYLON.serialize()
  47030. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47031. return ArcRotateCameraMouseWheelInput;
  47032. }());
  47033. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47034. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47035. })(BABYLON || (BABYLON = {}));
  47036. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47037. var BABYLON;
  47038. (function (BABYLON) {
  47039. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47040. function ArcRotateCameraPointersInput() {
  47041. this.buttons = [0, 1, 2];
  47042. this.angularSensibilityX = 1000.0;
  47043. this.angularSensibilityY = 1000.0;
  47044. this.pinchPrecision = 12.0;
  47045. /**
  47046. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47047. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47048. */
  47049. this.pinchDeltaPercentage = 0;
  47050. this.panningSensibility = 1000.0;
  47051. this.multiTouchPanning = true;
  47052. this.multiTouchPanAndZoom = true;
  47053. this._isPanClick = false;
  47054. this.pinchInwards = true;
  47055. }
  47056. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47057. var _this = this;
  47058. var engine = this.camera.getEngine();
  47059. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47060. var pointA = null;
  47061. var pointB = null;
  47062. var previousPinchSquaredDistance = 0;
  47063. var initialDistance = 0;
  47064. var twoFingerActivityCount = 0;
  47065. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47066. this._pointerInput = function (p, s) {
  47067. var evt = p.event;
  47068. var isTouch = p.event.pointerType === "touch";
  47069. if (engine.isInVRExclusivePointerMode) {
  47070. return;
  47071. }
  47072. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47073. return;
  47074. }
  47075. var srcElement = (evt.srcElement || evt.target);
  47076. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47077. try {
  47078. srcElement.setPointerCapture(evt.pointerId);
  47079. }
  47080. catch (e) {
  47081. //Nothing to do with the error. Execution will continue.
  47082. }
  47083. // Manage panning with pan button click
  47084. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47085. // manage pointers
  47086. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47087. if (pointA === null) {
  47088. pointA = cacheSoloPointer;
  47089. }
  47090. else if (pointB === null) {
  47091. pointB = cacheSoloPointer;
  47092. }
  47093. if (!noPreventDefault) {
  47094. evt.preventDefault();
  47095. element.focus();
  47096. }
  47097. }
  47098. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47099. _this.camera.restoreState();
  47100. }
  47101. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47102. try {
  47103. srcElement.releasePointerCapture(evt.pointerId);
  47104. }
  47105. catch (e) {
  47106. //Nothing to do with the error.
  47107. }
  47108. cacheSoloPointer = null;
  47109. previousPinchSquaredDistance = 0;
  47110. previousMultiTouchPanPosition.isPaning = false;
  47111. previousMultiTouchPanPosition.isPinching = false;
  47112. twoFingerActivityCount = 0;
  47113. initialDistance = 0;
  47114. if (!isTouch) {
  47115. pointB = null; // Mouse and pen are mono pointer
  47116. }
  47117. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47118. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47119. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47120. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47121. if (engine._badOS) {
  47122. pointA = pointB = null;
  47123. }
  47124. else {
  47125. //only remove the impacted pointer in case of multitouch allowing on most
  47126. //platforms switching from rotate to zoom and pan seamlessly.
  47127. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47128. pointA = pointB;
  47129. pointB = null;
  47130. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47131. }
  47132. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47133. pointB = null;
  47134. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47135. }
  47136. else {
  47137. pointA = pointB = null;
  47138. }
  47139. }
  47140. if (!noPreventDefault) {
  47141. evt.preventDefault();
  47142. }
  47143. }
  47144. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47145. if (!noPreventDefault) {
  47146. evt.preventDefault();
  47147. }
  47148. // One button down
  47149. if (pointA && pointB === null && cacheSoloPointer) {
  47150. if (_this.panningSensibility !== 0 &&
  47151. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47152. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47153. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47154. }
  47155. else {
  47156. var offsetX = evt.clientX - cacheSoloPointer.x;
  47157. var offsetY = evt.clientY - cacheSoloPointer.y;
  47158. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47159. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47160. }
  47161. cacheSoloPointer.x = evt.clientX;
  47162. cacheSoloPointer.y = evt.clientY;
  47163. }
  47164. // Two buttons down: pinch/pan
  47165. else if (pointA && pointB) {
  47166. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47167. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47168. ed.x = evt.clientX;
  47169. ed.y = evt.clientY;
  47170. var direction = _this.pinchInwards ? 1 : -1;
  47171. var distX = pointA.x - pointB.x;
  47172. var distY = pointA.y - pointB.y;
  47173. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47174. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47175. if (previousPinchSquaredDistance === 0) {
  47176. initialDistance = pinchDistance;
  47177. previousPinchSquaredDistance = pinchSquaredDistance;
  47178. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47179. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47180. return;
  47181. }
  47182. if (_this.multiTouchPanAndZoom) {
  47183. if (_this.pinchDeltaPercentage) {
  47184. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47185. }
  47186. else {
  47187. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47188. (_this.pinchPrecision *
  47189. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47190. direction);
  47191. }
  47192. if (_this.panningSensibility !== 0) {
  47193. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47194. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47195. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47196. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47197. previousMultiTouchPanPosition.x = pointersCenterX;
  47198. previousMultiTouchPanPosition.y = pointersCenterY;
  47199. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47200. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47201. }
  47202. }
  47203. else {
  47204. twoFingerActivityCount++;
  47205. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47206. if (_this.pinchDeltaPercentage) {
  47207. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47208. }
  47209. else {
  47210. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47211. (_this.pinchPrecision *
  47212. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47213. direction);
  47214. }
  47215. previousMultiTouchPanPosition.isPaning = false;
  47216. previousMultiTouchPanPosition.isPinching = true;
  47217. }
  47218. else {
  47219. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47220. if (!previousMultiTouchPanPosition.isPaning) {
  47221. previousMultiTouchPanPosition.isPaning = true;
  47222. previousMultiTouchPanPosition.isPinching = false;
  47223. previousMultiTouchPanPosition.x = ed.x;
  47224. previousMultiTouchPanPosition.y = ed.y;
  47225. return;
  47226. }
  47227. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47228. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47229. }
  47230. }
  47231. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47232. previousMultiTouchPanPosition.x = ed.x;
  47233. previousMultiTouchPanPosition.y = ed.y;
  47234. }
  47235. }
  47236. previousPinchSquaredDistance = pinchSquaredDistance;
  47237. }
  47238. }
  47239. };
  47240. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47241. this._onContextMenu = function (evt) {
  47242. evt.preventDefault();
  47243. };
  47244. if (!this.camera._useCtrlForPanning) {
  47245. element.addEventListener("contextmenu", this._onContextMenu, false);
  47246. }
  47247. this._onLostFocus = function () {
  47248. //this._keys = [];
  47249. pointA = pointB = null;
  47250. previousPinchSquaredDistance = 0;
  47251. previousMultiTouchPanPosition.isPaning = false;
  47252. previousMultiTouchPanPosition.isPinching = false;
  47253. twoFingerActivityCount = 0;
  47254. cacheSoloPointer = null;
  47255. initialDistance = 0;
  47256. };
  47257. this._onMouseMove = function (evt) {
  47258. if (!engine.isPointerLock) {
  47259. return;
  47260. }
  47261. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47262. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47263. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47264. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47265. if (!noPreventDefault) {
  47266. evt.preventDefault();
  47267. }
  47268. };
  47269. this._onGestureStart = function (e) {
  47270. if (window.MSGesture === undefined) {
  47271. return;
  47272. }
  47273. if (!_this._MSGestureHandler) {
  47274. _this._MSGestureHandler = new MSGesture();
  47275. _this._MSGestureHandler.target = element;
  47276. }
  47277. _this._MSGestureHandler.addPointer(e.pointerId);
  47278. };
  47279. this._onGesture = function (e) {
  47280. _this.camera.radius *= e.scale;
  47281. if (e.preventDefault) {
  47282. if (!noPreventDefault) {
  47283. e.stopPropagation();
  47284. e.preventDefault();
  47285. }
  47286. }
  47287. };
  47288. element.addEventListener("mousemove", this._onMouseMove, false);
  47289. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47290. element.addEventListener("MSGestureChange", this._onGesture, false);
  47291. BABYLON.Tools.RegisterTopRootEvents([
  47292. { name: "blur", handler: this._onLostFocus }
  47293. ]);
  47294. };
  47295. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47296. if (this._onLostFocus) {
  47297. BABYLON.Tools.UnregisterTopRootEvents([
  47298. { name: "blur", handler: this._onLostFocus }
  47299. ]);
  47300. }
  47301. if (element && this._observer) {
  47302. this.camera.getScene().onPointerObservable.remove(this._observer);
  47303. this._observer = null;
  47304. if (this._onContextMenu) {
  47305. element.removeEventListener("contextmenu", this._onContextMenu);
  47306. }
  47307. if (this._onMouseMove) {
  47308. element.removeEventListener("mousemove", this._onMouseMove);
  47309. }
  47310. if (this._onGestureStart) {
  47311. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47312. }
  47313. if (this._onGesture) {
  47314. element.removeEventListener("MSGestureChange", this._onGesture);
  47315. }
  47316. this._isPanClick = false;
  47317. this.pinchInwards = true;
  47318. this._onMouseMove = null;
  47319. this._onGestureStart = null;
  47320. this._onGesture = null;
  47321. this._MSGestureHandler = null;
  47322. this._onLostFocus = null;
  47323. this._onContextMenu = null;
  47324. }
  47325. };
  47326. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47327. return "ArcRotateCameraPointersInput";
  47328. };
  47329. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47330. return "pointers";
  47331. };
  47332. __decorate([
  47333. BABYLON.serialize()
  47334. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47335. __decorate([
  47336. BABYLON.serialize()
  47337. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47338. __decorate([
  47339. BABYLON.serialize()
  47340. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47341. __decorate([
  47342. BABYLON.serialize()
  47343. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47344. __decorate([
  47345. BABYLON.serialize()
  47346. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47347. __decorate([
  47348. BABYLON.serialize()
  47349. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47350. __decorate([
  47351. BABYLON.serialize()
  47352. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47353. __decorate([
  47354. BABYLON.serialize()
  47355. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47356. return ArcRotateCameraPointersInput;
  47357. }());
  47358. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47359. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47360. })(BABYLON || (BABYLON = {}));
  47361. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47362. var BABYLON;
  47363. (function (BABYLON) {
  47364. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47365. __extends(ArcRotateCameraInputsManager, _super);
  47366. function ArcRotateCameraInputsManager(camera) {
  47367. return _super.call(this, camera) || this;
  47368. }
  47369. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47370. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47371. return this;
  47372. };
  47373. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47374. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47375. return this;
  47376. };
  47377. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47378. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47379. return this;
  47380. };
  47381. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47382. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47383. return this;
  47384. };
  47385. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47386. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47387. return this;
  47388. };
  47389. return ArcRotateCameraInputsManager;
  47390. }(BABYLON.CameraInputsManager));
  47391. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47392. })(BABYLON || (BABYLON = {}));
  47393. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47394. var BABYLON;
  47395. (function (BABYLON) {
  47396. var ArcRotateCamera = /** @class */ (function (_super) {
  47397. __extends(ArcRotateCamera, _super);
  47398. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47399. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47400. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47401. _this.inertialAlphaOffset = 0;
  47402. _this.inertialBetaOffset = 0;
  47403. _this.inertialRadiusOffset = 0;
  47404. _this.lowerAlphaLimit = null;
  47405. _this.upperAlphaLimit = null;
  47406. _this.lowerBetaLimit = 0.01;
  47407. _this.upperBetaLimit = Math.PI;
  47408. _this.lowerRadiusLimit = null;
  47409. _this.upperRadiusLimit = null;
  47410. _this.inertialPanningX = 0;
  47411. _this.inertialPanningY = 0;
  47412. _this.pinchToPanMaxDistance = 20;
  47413. _this.panningDistanceLimit = null;
  47414. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47415. _this.panningInertia = 0.9;
  47416. //-- end properties for backward compatibility for inputs
  47417. _this.zoomOnFactor = 1;
  47418. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47419. _this.allowUpsideDown = true;
  47420. _this._viewMatrix = new BABYLON.Matrix();
  47421. // Panning
  47422. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47423. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47424. _this.checkCollisions = false;
  47425. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47426. _this._previousPosition = BABYLON.Vector3.Zero();
  47427. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47428. _this._newPosition = BABYLON.Vector3.Zero();
  47429. _this._computationVector = BABYLON.Vector3.Zero();
  47430. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47431. if (collidedMesh === void 0) { collidedMesh = null; }
  47432. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47433. newPosition.multiplyInPlace(_this._collider._radius);
  47434. }
  47435. if (!collidedMesh) {
  47436. _this._previousPosition.copyFrom(_this.position);
  47437. }
  47438. else {
  47439. _this.setPosition(newPosition);
  47440. if (_this.onCollide) {
  47441. _this.onCollide(collidedMesh);
  47442. }
  47443. }
  47444. // Recompute because of constraints
  47445. var cosa = Math.cos(_this.alpha);
  47446. var sina = Math.sin(_this.alpha);
  47447. var cosb = Math.cos(_this.beta);
  47448. var sinb = Math.sin(_this.beta);
  47449. if (sinb === 0) {
  47450. sinb = 0.0001;
  47451. }
  47452. var target = _this._getTargetPosition();
  47453. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47454. target.addToRef(_this._computationVector, _this._newPosition);
  47455. _this.position.copyFrom(_this._newPosition);
  47456. var up = _this.upVector;
  47457. if (_this.allowUpsideDown && _this.beta < 0) {
  47458. up = up.clone();
  47459. up = up.negate();
  47460. }
  47461. _this._computeViewMatrix(_this.position, target, up);
  47462. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47463. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47464. _this._collisionTriggered = false;
  47465. };
  47466. _this._target = BABYLON.Vector3.Zero();
  47467. if (target) {
  47468. _this.setTarget(target);
  47469. }
  47470. _this.alpha = alpha;
  47471. _this.beta = beta;
  47472. _this.radius = radius;
  47473. _this.getViewMatrix();
  47474. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47475. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47476. return _this;
  47477. }
  47478. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47479. get: function () {
  47480. return this._target;
  47481. },
  47482. set: function (value) {
  47483. this.setTarget(value);
  47484. },
  47485. enumerable: true,
  47486. configurable: true
  47487. });
  47488. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47489. //-- begin properties for backward compatibility for inputs
  47490. get: function () {
  47491. var pointers = this.inputs.attached["pointers"];
  47492. if (pointers)
  47493. return pointers.angularSensibilityX;
  47494. return 0;
  47495. },
  47496. set: function (value) {
  47497. var pointers = this.inputs.attached["pointers"];
  47498. if (pointers) {
  47499. pointers.angularSensibilityX = value;
  47500. }
  47501. },
  47502. enumerable: true,
  47503. configurable: true
  47504. });
  47505. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47506. get: function () {
  47507. var pointers = this.inputs.attached["pointers"];
  47508. if (pointers)
  47509. return pointers.angularSensibilityY;
  47510. return 0;
  47511. },
  47512. set: function (value) {
  47513. var pointers = this.inputs.attached["pointers"];
  47514. if (pointers) {
  47515. pointers.angularSensibilityY = value;
  47516. }
  47517. },
  47518. enumerable: true,
  47519. configurable: true
  47520. });
  47521. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47522. get: function () {
  47523. var pointers = this.inputs.attached["pointers"];
  47524. if (pointers)
  47525. return pointers.pinchPrecision;
  47526. return 0;
  47527. },
  47528. set: function (value) {
  47529. var pointers = this.inputs.attached["pointers"];
  47530. if (pointers) {
  47531. pointers.pinchPrecision = value;
  47532. }
  47533. },
  47534. enumerable: true,
  47535. configurable: true
  47536. });
  47537. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47538. get: function () {
  47539. var pointers = this.inputs.attached["pointers"];
  47540. if (pointers)
  47541. return pointers.pinchDeltaPercentage;
  47542. return 0;
  47543. },
  47544. set: function (value) {
  47545. var pointers = this.inputs.attached["pointers"];
  47546. if (pointers) {
  47547. pointers.pinchDeltaPercentage = value;
  47548. }
  47549. },
  47550. enumerable: true,
  47551. configurable: true
  47552. });
  47553. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47554. get: function () {
  47555. var pointers = this.inputs.attached["pointers"];
  47556. if (pointers)
  47557. return pointers.panningSensibility;
  47558. return 0;
  47559. },
  47560. set: function (value) {
  47561. var pointers = this.inputs.attached["pointers"];
  47562. if (pointers) {
  47563. pointers.panningSensibility = value;
  47564. }
  47565. },
  47566. enumerable: true,
  47567. configurable: true
  47568. });
  47569. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47570. get: function () {
  47571. var keyboard = this.inputs.attached["keyboard"];
  47572. if (keyboard)
  47573. return keyboard.keysUp;
  47574. return [];
  47575. },
  47576. set: function (value) {
  47577. var keyboard = this.inputs.attached["keyboard"];
  47578. if (keyboard)
  47579. keyboard.keysUp = value;
  47580. },
  47581. enumerable: true,
  47582. configurable: true
  47583. });
  47584. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47585. get: function () {
  47586. var keyboard = this.inputs.attached["keyboard"];
  47587. if (keyboard)
  47588. return keyboard.keysDown;
  47589. return [];
  47590. },
  47591. set: function (value) {
  47592. var keyboard = this.inputs.attached["keyboard"];
  47593. if (keyboard)
  47594. keyboard.keysDown = value;
  47595. },
  47596. enumerable: true,
  47597. configurable: true
  47598. });
  47599. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47600. get: function () {
  47601. var keyboard = this.inputs.attached["keyboard"];
  47602. if (keyboard)
  47603. return keyboard.keysLeft;
  47604. return [];
  47605. },
  47606. set: function (value) {
  47607. var keyboard = this.inputs.attached["keyboard"];
  47608. if (keyboard)
  47609. keyboard.keysLeft = value;
  47610. },
  47611. enumerable: true,
  47612. configurable: true
  47613. });
  47614. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47615. get: function () {
  47616. var keyboard = this.inputs.attached["keyboard"];
  47617. if (keyboard)
  47618. return keyboard.keysRight;
  47619. return [];
  47620. },
  47621. set: function (value) {
  47622. var keyboard = this.inputs.attached["keyboard"];
  47623. if (keyboard)
  47624. keyboard.keysRight = value;
  47625. },
  47626. enumerable: true,
  47627. configurable: true
  47628. });
  47629. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47630. get: function () {
  47631. var mousewheel = this.inputs.attached["mousewheel"];
  47632. if (mousewheel)
  47633. return mousewheel.wheelPrecision;
  47634. return 0;
  47635. },
  47636. set: function (value) {
  47637. var mousewheel = this.inputs.attached["mousewheel"];
  47638. if (mousewheel)
  47639. mousewheel.wheelPrecision = value;
  47640. },
  47641. enumerable: true,
  47642. configurable: true
  47643. });
  47644. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47645. get: function () {
  47646. var mousewheel = this.inputs.attached["mousewheel"];
  47647. if (mousewheel)
  47648. return mousewheel.wheelDeltaPercentage;
  47649. return 0;
  47650. },
  47651. set: function (value) {
  47652. var mousewheel = this.inputs.attached["mousewheel"];
  47653. if (mousewheel)
  47654. mousewheel.wheelDeltaPercentage = value;
  47655. },
  47656. enumerable: true,
  47657. configurable: true
  47658. });
  47659. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47660. get: function () {
  47661. return this._bouncingBehavior;
  47662. },
  47663. enumerable: true,
  47664. configurable: true
  47665. });
  47666. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47667. get: function () {
  47668. return this._bouncingBehavior != null;
  47669. },
  47670. set: function (value) {
  47671. if (value === this.useBouncingBehavior) {
  47672. return;
  47673. }
  47674. if (value) {
  47675. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47676. this.addBehavior(this._bouncingBehavior);
  47677. }
  47678. else if (this._bouncingBehavior) {
  47679. this.removeBehavior(this._bouncingBehavior);
  47680. this._bouncingBehavior = null;
  47681. }
  47682. },
  47683. enumerable: true,
  47684. configurable: true
  47685. });
  47686. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47687. get: function () {
  47688. return this._framingBehavior;
  47689. },
  47690. enumerable: true,
  47691. configurable: true
  47692. });
  47693. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47694. get: function () {
  47695. return this._framingBehavior != null;
  47696. },
  47697. set: function (value) {
  47698. if (value === this.useFramingBehavior) {
  47699. return;
  47700. }
  47701. if (value) {
  47702. this._framingBehavior = new BABYLON.FramingBehavior();
  47703. this.addBehavior(this._framingBehavior);
  47704. }
  47705. else if (this._framingBehavior) {
  47706. this.removeBehavior(this._framingBehavior);
  47707. this._framingBehavior = null;
  47708. }
  47709. },
  47710. enumerable: true,
  47711. configurable: true
  47712. });
  47713. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47714. get: function () {
  47715. return this._autoRotationBehavior;
  47716. },
  47717. enumerable: true,
  47718. configurable: true
  47719. });
  47720. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47721. get: function () {
  47722. return this._autoRotationBehavior != null;
  47723. },
  47724. set: function (value) {
  47725. if (value === this.useAutoRotationBehavior) {
  47726. return;
  47727. }
  47728. if (value) {
  47729. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47730. this.addBehavior(this._autoRotationBehavior);
  47731. }
  47732. else if (this._autoRotationBehavior) {
  47733. this.removeBehavior(this._autoRotationBehavior);
  47734. this._autoRotationBehavior = null;
  47735. }
  47736. },
  47737. enumerable: true,
  47738. configurable: true
  47739. });
  47740. // Cache
  47741. ArcRotateCamera.prototype._initCache = function () {
  47742. _super.prototype._initCache.call(this);
  47743. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47744. this._cache.alpha = undefined;
  47745. this._cache.beta = undefined;
  47746. this._cache.radius = undefined;
  47747. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47748. };
  47749. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47750. if (!ignoreParentClass) {
  47751. _super.prototype._updateCache.call(this);
  47752. }
  47753. this._cache._target.copyFrom(this._getTargetPosition());
  47754. this._cache.alpha = this.alpha;
  47755. this._cache.beta = this.beta;
  47756. this._cache.radius = this.radius;
  47757. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47758. };
  47759. ArcRotateCamera.prototype._getTargetPosition = function () {
  47760. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47761. var pos = this._targetHost.getAbsolutePosition();
  47762. if (this._targetBoundingCenter) {
  47763. pos.addToRef(this._targetBoundingCenter, this._target);
  47764. }
  47765. else {
  47766. this._target.copyFrom(pos);
  47767. }
  47768. }
  47769. var lockedTargetPosition = this._getLockedTargetPosition();
  47770. if (lockedTargetPosition) {
  47771. return lockedTargetPosition;
  47772. }
  47773. return this._target;
  47774. };
  47775. ArcRotateCamera.prototype.storeState = function () {
  47776. this._storedAlpha = this.alpha;
  47777. this._storedBeta = this.beta;
  47778. this._storedRadius = this.radius;
  47779. this._storedTarget = this._getTargetPosition().clone();
  47780. return _super.prototype.storeState.call(this);
  47781. };
  47782. /**
  47783. * Restored camera state. You must call storeState() first
  47784. */
  47785. ArcRotateCamera.prototype._restoreStateValues = function () {
  47786. if (!_super.prototype._restoreStateValues.call(this)) {
  47787. return false;
  47788. }
  47789. this.alpha = this._storedAlpha;
  47790. this.beta = this._storedBeta;
  47791. this.radius = this._storedRadius;
  47792. this.setTarget(this._storedTarget.clone());
  47793. this.inertialAlphaOffset = 0;
  47794. this.inertialBetaOffset = 0;
  47795. this.inertialRadiusOffset = 0;
  47796. this.inertialPanningX = 0;
  47797. this.inertialPanningY = 0;
  47798. return true;
  47799. };
  47800. // Synchronized
  47801. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47802. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47803. return false;
  47804. return this._cache._target.equals(this._getTargetPosition())
  47805. && this._cache.alpha === this.alpha
  47806. && this._cache.beta === this.beta
  47807. && this._cache.radius === this.radius
  47808. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47809. };
  47810. // Methods
  47811. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47812. var _this = this;
  47813. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47814. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47815. this._useCtrlForPanning = useCtrlForPanning;
  47816. this._panningMouseButton = panningMouseButton;
  47817. this.inputs.attachElement(element, noPreventDefault);
  47818. this._reset = function () {
  47819. _this.inertialAlphaOffset = 0;
  47820. _this.inertialBetaOffset = 0;
  47821. _this.inertialRadiusOffset = 0;
  47822. _this.inertialPanningX = 0;
  47823. _this.inertialPanningY = 0;
  47824. };
  47825. };
  47826. ArcRotateCamera.prototype.detachControl = function (element) {
  47827. this.inputs.detachElement(element);
  47828. if (this._reset) {
  47829. this._reset();
  47830. }
  47831. };
  47832. ArcRotateCamera.prototype._checkInputs = function () {
  47833. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47834. if (this._collisionTriggered) {
  47835. return;
  47836. }
  47837. this.inputs.checkInputs();
  47838. // Inertia
  47839. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47840. var inertialAlphaOffset = this.inertialAlphaOffset;
  47841. if (this.beta <= 0)
  47842. inertialAlphaOffset *= -1;
  47843. if (this.getScene().useRightHandedSystem)
  47844. inertialAlphaOffset *= -1;
  47845. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47846. inertialAlphaOffset *= -1;
  47847. this.alpha += inertialAlphaOffset;
  47848. this.beta += this.inertialBetaOffset;
  47849. this.radius -= this.inertialRadiusOffset;
  47850. this.inertialAlphaOffset *= this.inertia;
  47851. this.inertialBetaOffset *= this.inertia;
  47852. this.inertialRadiusOffset *= this.inertia;
  47853. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47854. this.inertialAlphaOffset = 0;
  47855. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47856. this.inertialBetaOffset = 0;
  47857. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47858. this.inertialRadiusOffset = 0;
  47859. }
  47860. // Panning inertia
  47861. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47862. if (!this._localDirection) {
  47863. this._localDirection = BABYLON.Vector3.Zero();
  47864. this._transformedDirection = BABYLON.Vector3.Zero();
  47865. }
  47866. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47867. this._localDirection.multiplyInPlace(this.panningAxis);
  47868. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47869. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47870. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47871. if (!this.panningAxis.y) {
  47872. this._transformedDirection.y = 0;
  47873. }
  47874. if (!this._targetHost) {
  47875. if (this.panningDistanceLimit) {
  47876. this._transformedDirection.addInPlace(this._target);
  47877. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47878. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47879. this._target.copyFrom(this._transformedDirection);
  47880. }
  47881. }
  47882. else {
  47883. this._target.addInPlace(this._transformedDirection);
  47884. }
  47885. }
  47886. this.inertialPanningX *= this.panningInertia;
  47887. this.inertialPanningY *= this.panningInertia;
  47888. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47889. this.inertialPanningX = 0;
  47890. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47891. this.inertialPanningY = 0;
  47892. }
  47893. // Limits
  47894. this._checkLimits();
  47895. _super.prototype._checkInputs.call(this);
  47896. };
  47897. ArcRotateCamera.prototype._checkLimits = function () {
  47898. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47899. if (this.allowUpsideDown && this.beta > Math.PI) {
  47900. this.beta = this.beta - (2 * Math.PI);
  47901. }
  47902. }
  47903. else {
  47904. if (this.beta < this.lowerBetaLimit) {
  47905. this.beta = this.lowerBetaLimit;
  47906. }
  47907. }
  47908. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47909. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47910. this.beta = this.beta + (2 * Math.PI);
  47911. }
  47912. }
  47913. else {
  47914. if (this.beta > this.upperBetaLimit) {
  47915. this.beta = this.upperBetaLimit;
  47916. }
  47917. }
  47918. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47919. this.alpha = this.lowerAlphaLimit;
  47920. }
  47921. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47922. this.alpha = this.upperAlphaLimit;
  47923. }
  47924. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47925. this.radius = this.lowerRadiusLimit;
  47926. }
  47927. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47928. this.radius = this.upperRadiusLimit;
  47929. }
  47930. };
  47931. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47932. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47933. this.radius = this._computationVector.length();
  47934. if (this.radius === 0) {
  47935. this.radius = 0.0001; // Just to avoid division by zero
  47936. }
  47937. // Alpha
  47938. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47939. if (this._computationVector.z < 0) {
  47940. this.alpha = 2 * Math.PI - this.alpha;
  47941. }
  47942. // Beta
  47943. this.beta = Math.acos(this._computationVector.y / this.radius);
  47944. this._checkLimits();
  47945. };
  47946. ArcRotateCamera.prototype.setPosition = function (position) {
  47947. if (this.position.equals(position)) {
  47948. return;
  47949. }
  47950. this.position.copyFrom(position);
  47951. this.rebuildAnglesAndRadius();
  47952. };
  47953. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47954. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47955. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47956. if (target.getBoundingInfo) {
  47957. if (toBoundingCenter) {
  47958. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47959. }
  47960. else {
  47961. this._targetBoundingCenter = null;
  47962. }
  47963. this._targetHost = target;
  47964. this._target = this._getTargetPosition();
  47965. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47966. }
  47967. else {
  47968. var newTarget = target;
  47969. var currentTarget = this._getTargetPosition();
  47970. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47971. return;
  47972. }
  47973. this._targetHost = null;
  47974. this._target = newTarget;
  47975. this._targetBoundingCenter = null;
  47976. this.onMeshTargetChangedObservable.notifyObservers(null);
  47977. }
  47978. this.rebuildAnglesAndRadius();
  47979. };
  47980. ArcRotateCamera.prototype._getViewMatrix = function () {
  47981. // Compute
  47982. var cosa = Math.cos(this.alpha);
  47983. var sina = Math.sin(this.alpha);
  47984. var cosb = Math.cos(this.beta);
  47985. var sinb = Math.sin(this.beta);
  47986. if (sinb === 0) {
  47987. sinb = 0.0001;
  47988. }
  47989. var target = this._getTargetPosition();
  47990. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47991. target.addToRef(this._computationVector, this._newPosition);
  47992. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47993. if (!this._collider) {
  47994. this._collider = new BABYLON.Collider();
  47995. }
  47996. this._collider._radius = this.collisionRadius;
  47997. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47998. this._collisionTriggered = true;
  47999. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48000. }
  48001. else {
  48002. this.position.copyFrom(this._newPosition);
  48003. var up = this.upVector;
  48004. if (this.allowUpsideDown && sinb < 0) {
  48005. up = up.clone();
  48006. up = up.negate();
  48007. }
  48008. this._computeViewMatrix(this.position, target, up);
  48009. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48010. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48011. }
  48012. this._currentTarget = target;
  48013. return this._viewMatrix;
  48014. };
  48015. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48016. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48017. meshes = meshes || this.getScene().meshes;
  48018. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48019. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48020. this.radius = distance * this.zoomOnFactor;
  48021. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48022. };
  48023. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48024. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48025. var meshesOrMinMaxVector;
  48026. var distance;
  48027. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48028. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48029. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48030. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48031. }
  48032. else { //minMaxVector and distance
  48033. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48034. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48035. distance = minMaxVectorAndDistance.distance;
  48036. }
  48037. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48038. if (!doNotUpdateMaxZ) {
  48039. this.maxZ = distance * 2;
  48040. }
  48041. };
  48042. /**
  48043. * @override
  48044. * Override Camera.createRigCamera
  48045. */
  48046. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48047. var alphaShift = 0;
  48048. switch (this.cameraRigMode) {
  48049. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48050. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48051. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48052. case BABYLON.Camera.RIG_MODE_VR:
  48053. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48054. break;
  48055. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48056. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48057. break;
  48058. }
  48059. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48060. rigCam._cameraRigParams = {};
  48061. return rigCam;
  48062. };
  48063. /**
  48064. * @override
  48065. * Override Camera._updateRigCameras
  48066. */
  48067. ArcRotateCamera.prototype._updateRigCameras = function () {
  48068. var camLeft = this._rigCameras[0];
  48069. var camRight = this._rigCameras[1];
  48070. camLeft.beta = camRight.beta = this.beta;
  48071. camLeft.radius = camRight.radius = this.radius;
  48072. switch (this.cameraRigMode) {
  48073. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48074. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48075. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48076. case BABYLON.Camera.RIG_MODE_VR:
  48077. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48078. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48079. break;
  48080. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48081. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48082. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48083. break;
  48084. }
  48085. _super.prototype._updateRigCameras.call(this);
  48086. };
  48087. ArcRotateCamera.prototype.dispose = function () {
  48088. this.inputs.clear();
  48089. _super.prototype.dispose.call(this);
  48090. };
  48091. ArcRotateCamera.prototype.getClassName = function () {
  48092. return "ArcRotateCamera";
  48093. };
  48094. __decorate([
  48095. BABYLON.serialize()
  48096. ], ArcRotateCamera.prototype, "alpha", void 0);
  48097. __decorate([
  48098. BABYLON.serialize()
  48099. ], ArcRotateCamera.prototype, "beta", void 0);
  48100. __decorate([
  48101. BABYLON.serialize()
  48102. ], ArcRotateCamera.prototype, "radius", void 0);
  48103. __decorate([
  48104. BABYLON.serializeAsVector3("target")
  48105. ], ArcRotateCamera.prototype, "_target", void 0);
  48106. __decorate([
  48107. BABYLON.serialize()
  48108. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48109. __decorate([
  48110. BABYLON.serialize()
  48111. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48112. __decorate([
  48113. BABYLON.serialize()
  48114. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48115. __decorate([
  48116. BABYLON.serialize()
  48117. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48118. __decorate([
  48119. BABYLON.serialize()
  48120. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48121. __decorate([
  48122. BABYLON.serialize()
  48123. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48124. __decorate([
  48125. BABYLON.serialize()
  48126. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48127. __decorate([
  48128. BABYLON.serialize()
  48129. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48130. __decorate([
  48131. BABYLON.serialize()
  48132. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48133. __decorate([
  48134. BABYLON.serialize()
  48135. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48136. __decorate([
  48137. BABYLON.serialize()
  48138. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48139. __decorate([
  48140. BABYLON.serialize()
  48141. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48142. __decorate([
  48143. BABYLON.serialize()
  48144. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48145. __decorate([
  48146. BABYLON.serializeAsVector3()
  48147. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48148. __decorate([
  48149. BABYLON.serialize()
  48150. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48151. __decorate([
  48152. BABYLON.serialize()
  48153. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48154. __decorate([
  48155. BABYLON.serialize()
  48156. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48157. return ArcRotateCamera;
  48158. }(BABYLON.TargetCamera));
  48159. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48160. })(BABYLON || (BABYLON = {}));
  48161. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48162. var BABYLON;
  48163. (function (BABYLON) {
  48164. /**
  48165. * The HemisphericLight simulates the ambient environment light,
  48166. * so the passed direction is the light reflection direction, not the incoming direction.
  48167. */
  48168. var HemisphericLight = /** @class */ (function (_super) {
  48169. __extends(HemisphericLight, _super);
  48170. /**
  48171. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48172. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48173. * The HemisphericLight can't cast shadows.
  48174. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48175. * @param name The friendly name of the light
  48176. * @param direction The direction of the light reflection
  48177. * @param scene The scene the light belongs to
  48178. */
  48179. function HemisphericLight(name, direction, scene) {
  48180. var _this = _super.call(this, name, scene) || this;
  48181. /**
  48182. * The groundColor is the light in the opposite direction to the one specified during creation.
  48183. * 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.
  48184. */
  48185. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48186. _this.direction = direction || BABYLON.Vector3.Up();
  48187. return _this;
  48188. }
  48189. HemisphericLight.prototype._buildUniformLayout = function () {
  48190. this._uniformBuffer.addUniform("vLightData", 4);
  48191. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48192. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48193. this._uniformBuffer.addUniform("vLightGround", 3);
  48194. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48195. this._uniformBuffer.addUniform("depthValues", 2);
  48196. this._uniformBuffer.create();
  48197. };
  48198. /**
  48199. * Returns the string "HemisphericLight".
  48200. * @return The class name
  48201. */
  48202. HemisphericLight.prototype.getClassName = function () {
  48203. return "HemisphericLight";
  48204. };
  48205. /**
  48206. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48207. * Returns the updated direction.
  48208. * @param target The target the direction should point to
  48209. * @return The computed direction
  48210. */
  48211. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48212. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48213. return this.direction;
  48214. };
  48215. /**
  48216. * Returns the shadow generator associated to the light.
  48217. * @returns Always null for hemispheric lights because it does not support shadows.
  48218. */
  48219. HemisphericLight.prototype.getShadowGenerator = function () {
  48220. return null;
  48221. };
  48222. /**
  48223. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48224. * @param effect The effect to update
  48225. * @param lightIndex The index of the light in the effect to update
  48226. * @returns The hemispheric light
  48227. */
  48228. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48229. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48230. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48231. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48232. return this;
  48233. };
  48234. /**
  48235. * @hidden internal use only.
  48236. */
  48237. HemisphericLight.prototype._getWorldMatrix = function () {
  48238. if (!this._worldMatrix) {
  48239. this._worldMatrix = BABYLON.Matrix.Identity();
  48240. }
  48241. return this._worldMatrix;
  48242. };
  48243. /**
  48244. * Returns the integer 3.
  48245. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48246. */
  48247. HemisphericLight.prototype.getTypeID = function () {
  48248. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48249. };
  48250. __decorate([
  48251. BABYLON.serializeAsColor3()
  48252. ], HemisphericLight.prototype, "groundColor", void 0);
  48253. __decorate([
  48254. BABYLON.serializeAsVector3()
  48255. ], HemisphericLight.prototype, "direction", void 0);
  48256. return HemisphericLight;
  48257. }(BABYLON.Light));
  48258. BABYLON.HemisphericLight = HemisphericLight;
  48259. })(BABYLON || (BABYLON = {}));
  48260. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48261. var BABYLON;
  48262. (function (BABYLON) {
  48263. /**
  48264. * Base implementation IShadowLight
  48265. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48266. */
  48267. var ShadowLight = /** @class */ (function (_super) {
  48268. __extends(ShadowLight, _super);
  48269. function ShadowLight() {
  48270. var _this = _super !== null && _super.apply(this, arguments) || this;
  48271. _this._needProjectionMatrixCompute = true;
  48272. return _this;
  48273. }
  48274. ShadowLight.prototype._setPosition = function (value) {
  48275. this._position = value;
  48276. };
  48277. Object.defineProperty(ShadowLight.prototype, "position", {
  48278. /**
  48279. * Sets the position the shadow will be casted from. Also use as the light position for both
  48280. * point and spot lights.
  48281. */
  48282. get: function () {
  48283. return this._position;
  48284. },
  48285. /**
  48286. * Sets the position the shadow will be casted from. Also use as the light position for both
  48287. * point and spot lights.
  48288. */
  48289. set: function (value) {
  48290. this._setPosition(value);
  48291. },
  48292. enumerable: true,
  48293. configurable: true
  48294. });
  48295. ShadowLight.prototype._setDirection = function (value) {
  48296. this._direction = value;
  48297. };
  48298. Object.defineProperty(ShadowLight.prototype, "direction", {
  48299. /**
  48300. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48301. * Also use as the light direction on spot and directional lights.
  48302. */
  48303. get: function () {
  48304. return this._direction;
  48305. },
  48306. /**
  48307. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48308. * Also use as the light direction on spot and directional lights.
  48309. */
  48310. set: function (value) {
  48311. this._setDirection(value);
  48312. },
  48313. enumerable: true,
  48314. configurable: true
  48315. });
  48316. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48317. /**
  48318. * Gets the shadow projection clipping minimum z value.
  48319. */
  48320. get: function () {
  48321. return this._shadowMinZ;
  48322. },
  48323. /**
  48324. * Sets the shadow projection clipping minimum z value.
  48325. */
  48326. set: function (value) {
  48327. this._shadowMinZ = value;
  48328. this.forceProjectionMatrixCompute();
  48329. },
  48330. enumerable: true,
  48331. configurable: true
  48332. });
  48333. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48334. /**
  48335. * Sets the shadow projection clipping maximum z value.
  48336. */
  48337. get: function () {
  48338. return this._shadowMaxZ;
  48339. },
  48340. /**
  48341. * Gets the shadow projection clipping maximum z value.
  48342. */
  48343. set: function (value) {
  48344. this._shadowMaxZ = value;
  48345. this.forceProjectionMatrixCompute();
  48346. },
  48347. enumerable: true,
  48348. configurable: true
  48349. });
  48350. /**
  48351. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48352. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48353. */
  48354. ShadowLight.prototype.computeTransformedInformation = function () {
  48355. if (this.parent && this.parent.getWorldMatrix) {
  48356. if (!this.transformedPosition) {
  48357. this.transformedPosition = BABYLON.Vector3.Zero();
  48358. }
  48359. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48360. // In case the direction is present.
  48361. if (this.direction) {
  48362. if (!this.transformedDirection) {
  48363. this.transformedDirection = BABYLON.Vector3.Zero();
  48364. }
  48365. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48366. }
  48367. return true;
  48368. }
  48369. return false;
  48370. };
  48371. /**
  48372. * Return the depth scale used for the shadow map.
  48373. * @returns the depth scale.
  48374. */
  48375. ShadowLight.prototype.getDepthScale = function () {
  48376. return 50.0;
  48377. };
  48378. /**
  48379. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48380. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48381. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48382. */
  48383. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48384. return this.transformedDirection ? this.transformedDirection : this.direction;
  48385. };
  48386. /**
  48387. * Returns the ShadowLight absolute position in the World.
  48388. * @returns the position vector in world space
  48389. */
  48390. ShadowLight.prototype.getAbsolutePosition = function () {
  48391. return this.transformedPosition ? this.transformedPosition : this.position;
  48392. };
  48393. /**
  48394. * Sets the ShadowLight direction toward the passed target.
  48395. * @param target The point tot target in local space
  48396. * @returns the updated ShadowLight direction
  48397. */
  48398. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48399. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48400. return this.direction;
  48401. };
  48402. /**
  48403. * Returns the light rotation in euler definition.
  48404. * @returns the x y z rotation in local space.
  48405. */
  48406. ShadowLight.prototype.getRotation = function () {
  48407. this.direction.normalize();
  48408. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48409. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48410. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48411. };
  48412. /**
  48413. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48414. * @returns true if a cube texture needs to be use
  48415. */
  48416. ShadowLight.prototype.needCube = function () {
  48417. return false;
  48418. };
  48419. /**
  48420. * Detects if the projection matrix requires to be recomputed this frame.
  48421. * @returns true if it requires to be recomputed otherwise, false.
  48422. */
  48423. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48424. return this._needProjectionMatrixCompute;
  48425. };
  48426. /**
  48427. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48428. */
  48429. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48430. this._needProjectionMatrixCompute = true;
  48431. };
  48432. /**
  48433. * Get the world matrix of the sahdow lights.
  48434. * @hidden Internal Use Only
  48435. */
  48436. ShadowLight.prototype._getWorldMatrix = function () {
  48437. if (!this._worldMatrix) {
  48438. this._worldMatrix = BABYLON.Matrix.Identity();
  48439. }
  48440. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48441. return this._worldMatrix;
  48442. };
  48443. /**
  48444. * Gets the minZ used for shadow according to both the scene and the light.
  48445. * @param activeCamera The camera we are returning the min for
  48446. * @returns the depth min z
  48447. */
  48448. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48449. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48450. };
  48451. /**
  48452. * Gets the maxZ used for shadow according to both the scene and the light.
  48453. * @param activeCamera The camera we are returning the max for
  48454. * @returns the depth max z
  48455. */
  48456. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48457. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48458. };
  48459. /**
  48460. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48461. * @param matrix The materix to updated with the projection information
  48462. * @param viewMatrix The transform matrix of the light
  48463. * @param renderList The list of mesh to render in the map
  48464. * @returns The current light
  48465. */
  48466. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48467. if (this.customProjectionMatrixBuilder) {
  48468. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48469. }
  48470. else {
  48471. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48472. }
  48473. return this;
  48474. };
  48475. __decorate([
  48476. BABYLON.serializeAsVector3()
  48477. ], ShadowLight.prototype, "position", null);
  48478. __decorate([
  48479. BABYLON.serializeAsVector3()
  48480. ], ShadowLight.prototype, "direction", null);
  48481. __decorate([
  48482. BABYLON.serialize()
  48483. ], ShadowLight.prototype, "shadowMinZ", null);
  48484. __decorate([
  48485. BABYLON.serialize()
  48486. ], ShadowLight.prototype, "shadowMaxZ", null);
  48487. return ShadowLight;
  48488. }(BABYLON.Light));
  48489. BABYLON.ShadowLight = ShadowLight;
  48490. })(BABYLON || (BABYLON = {}));
  48491. //# sourceMappingURL=babylon.shadowLight.js.map
  48492. var BABYLON;
  48493. (function (BABYLON) {
  48494. /**
  48495. * A point light is a light defined by an unique point in world space.
  48496. * The light is emitted in every direction from this point.
  48497. * A good example of a point light is a standard light bulb.
  48498. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48499. */
  48500. var PointLight = /** @class */ (function (_super) {
  48501. __extends(PointLight, _super);
  48502. /**
  48503. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48504. * A PointLight emits the light in every direction.
  48505. * It can cast shadows.
  48506. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48507. * ```javascript
  48508. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48509. * ```
  48510. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48511. * @param name The light friendly name
  48512. * @param position The position of the point light in the scene
  48513. * @param scene The scene the lights belongs to
  48514. */
  48515. function PointLight(name, position, scene) {
  48516. var _this = _super.call(this, name, scene) || this;
  48517. _this._shadowAngle = Math.PI / 2;
  48518. _this.position = position;
  48519. return _this;
  48520. }
  48521. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48522. /**
  48523. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48524. * This specifies what angle the shadow will use to be created.
  48525. *
  48526. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48527. */
  48528. get: function () {
  48529. return this._shadowAngle;
  48530. },
  48531. /**
  48532. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48533. * This specifies what angle the shadow will use to be created.
  48534. *
  48535. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48536. */
  48537. set: function (value) {
  48538. this._shadowAngle = value;
  48539. this.forceProjectionMatrixCompute();
  48540. },
  48541. enumerable: true,
  48542. configurable: true
  48543. });
  48544. Object.defineProperty(PointLight.prototype, "direction", {
  48545. /**
  48546. * Gets the direction if it has been set.
  48547. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48548. */
  48549. get: function () {
  48550. return this._direction;
  48551. },
  48552. /**
  48553. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48554. */
  48555. set: function (value) {
  48556. var previousNeedCube = this.needCube();
  48557. this._direction = value;
  48558. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48559. this._shadowGenerator.recreateShadowMap();
  48560. }
  48561. },
  48562. enumerable: true,
  48563. configurable: true
  48564. });
  48565. /**
  48566. * Returns the string "PointLight"
  48567. * @returns the class name
  48568. */
  48569. PointLight.prototype.getClassName = function () {
  48570. return "PointLight";
  48571. };
  48572. /**
  48573. * Returns the integer 0.
  48574. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48575. */
  48576. PointLight.prototype.getTypeID = function () {
  48577. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48578. };
  48579. /**
  48580. * Specifies wether or not the shadowmap should be a cube texture.
  48581. * @returns true if the shadowmap needs to be a cube texture.
  48582. */
  48583. PointLight.prototype.needCube = function () {
  48584. return !this.direction;
  48585. };
  48586. /**
  48587. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48588. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48589. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48590. */
  48591. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48592. if (this.direction) {
  48593. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48594. }
  48595. else {
  48596. switch (faceIndex) {
  48597. case 0:
  48598. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48599. case 1:
  48600. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48601. case 2:
  48602. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48603. case 3:
  48604. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48605. case 4:
  48606. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48607. case 5:
  48608. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48609. }
  48610. }
  48611. return BABYLON.Vector3.Zero();
  48612. };
  48613. /**
  48614. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48615. * - fov = PI / 2
  48616. * - aspect ratio : 1.0
  48617. * - z-near and far equal to the active camera minZ and maxZ.
  48618. * Returns the PointLight.
  48619. */
  48620. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48621. var activeCamera = this.getScene().activeCamera;
  48622. if (!activeCamera) {
  48623. return;
  48624. }
  48625. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48626. };
  48627. PointLight.prototype._buildUniformLayout = function () {
  48628. this._uniformBuffer.addUniform("vLightData", 4);
  48629. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48630. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48631. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48632. this._uniformBuffer.addUniform("depthValues", 2);
  48633. this._uniformBuffer.create();
  48634. };
  48635. /**
  48636. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48637. * @param effect The effect to update
  48638. * @param lightIndex The index of the light in the effect to update
  48639. * @returns The point light
  48640. */
  48641. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48642. if (this.computeTransformedInformation()) {
  48643. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48644. return this;
  48645. }
  48646. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48647. return this;
  48648. };
  48649. __decorate([
  48650. BABYLON.serialize()
  48651. ], PointLight.prototype, "shadowAngle", null);
  48652. return PointLight;
  48653. }(BABYLON.ShadowLight));
  48654. BABYLON.PointLight = PointLight;
  48655. })(BABYLON || (BABYLON = {}));
  48656. //# sourceMappingURL=babylon.pointLight.js.map
  48657. var BABYLON;
  48658. (function (BABYLON) {
  48659. /**
  48660. * A directional light is defined by a direction (what a surprise!).
  48661. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48662. * 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.
  48663. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48664. */
  48665. var DirectionalLight = /** @class */ (function (_super) {
  48666. __extends(DirectionalLight, _super);
  48667. /**
  48668. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48669. * The directional light is emitted from everywhere in the given direction.
  48670. * It can cast shawdows.
  48671. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48672. * @param name The friendly name of the light
  48673. * @param direction The direction of the light
  48674. * @param scene The scene the light belongs to
  48675. */
  48676. function DirectionalLight(name, direction, scene) {
  48677. var _this = _super.call(this, name, scene) || this;
  48678. _this._shadowFrustumSize = 0;
  48679. _this._shadowOrthoScale = 0.1;
  48680. /**
  48681. * Automatically compute the projection matrix to best fit (including all the casters)
  48682. * on each frame.
  48683. */
  48684. _this.autoUpdateExtends = true;
  48685. // Cache
  48686. _this._orthoLeft = Number.MAX_VALUE;
  48687. _this._orthoRight = Number.MIN_VALUE;
  48688. _this._orthoTop = Number.MIN_VALUE;
  48689. _this._orthoBottom = Number.MAX_VALUE;
  48690. _this.position = direction.scale(-1.0);
  48691. _this.direction = direction;
  48692. return _this;
  48693. }
  48694. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48695. /**
  48696. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48697. */
  48698. get: function () {
  48699. return this._shadowFrustumSize;
  48700. },
  48701. /**
  48702. * Specifies a fix frustum size for the shadow generation.
  48703. */
  48704. set: function (value) {
  48705. this._shadowFrustumSize = value;
  48706. this.forceProjectionMatrixCompute();
  48707. },
  48708. enumerable: true,
  48709. configurable: true
  48710. });
  48711. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48712. /**
  48713. * Gets the shadow projection scale against the optimal computed one.
  48714. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48715. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48716. */
  48717. get: function () {
  48718. return this._shadowOrthoScale;
  48719. },
  48720. /**
  48721. * Sets the shadow projection scale against the optimal computed one.
  48722. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48723. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48724. */
  48725. set: function (value) {
  48726. this._shadowOrthoScale = value;
  48727. this.forceProjectionMatrixCompute();
  48728. },
  48729. enumerable: true,
  48730. configurable: true
  48731. });
  48732. /**
  48733. * Returns the string "DirectionalLight".
  48734. * @return The class name
  48735. */
  48736. DirectionalLight.prototype.getClassName = function () {
  48737. return "DirectionalLight";
  48738. };
  48739. /**
  48740. * Returns the integer 1.
  48741. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48742. */
  48743. DirectionalLight.prototype.getTypeID = function () {
  48744. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48745. };
  48746. /**
  48747. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48748. * Returns the DirectionalLight Shadow projection matrix.
  48749. */
  48750. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48751. if (this.shadowFrustumSize > 0) {
  48752. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48753. }
  48754. else {
  48755. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48756. }
  48757. };
  48758. /**
  48759. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48760. * Returns the DirectionalLight Shadow projection matrix.
  48761. */
  48762. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48763. var activeCamera = this.getScene().activeCamera;
  48764. if (!activeCamera) {
  48765. return;
  48766. }
  48767. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48768. };
  48769. /**
  48770. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48771. * Returns the DirectionalLight Shadow projection matrix.
  48772. */
  48773. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48774. var activeCamera = this.getScene().activeCamera;
  48775. if (!activeCamera) {
  48776. return;
  48777. }
  48778. // Check extends
  48779. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48780. var tempVector3 = BABYLON.Vector3.Zero();
  48781. this._orthoLeft = Number.MAX_VALUE;
  48782. this._orthoRight = Number.MIN_VALUE;
  48783. this._orthoTop = Number.MIN_VALUE;
  48784. this._orthoBottom = Number.MAX_VALUE;
  48785. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48786. var mesh = renderList[meshIndex];
  48787. if (!mesh) {
  48788. continue;
  48789. }
  48790. var boundingInfo = mesh.getBoundingInfo();
  48791. var boundingBox = boundingInfo.boundingBox;
  48792. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48793. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48794. if (tempVector3.x < this._orthoLeft)
  48795. this._orthoLeft = tempVector3.x;
  48796. if (tempVector3.y < this._orthoBottom)
  48797. this._orthoBottom = tempVector3.y;
  48798. if (tempVector3.x > this._orthoRight)
  48799. this._orthoRight = tempVector3.x;
  48800. if (tempVector3.y > this._orthoTop)
  48801. this._orthoTop = tempVector3.y;
  48802. }
  48803. }
  48804. }
  48805. var xOffset = this._orthoRight - this._orthoLeft;
  48806. var yOffset = this._orthoTop - this._orthoBottom;
  48807. 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);
  48808. };
  48809. DirectionalLight.prototype._buildUniformLayout = function () {
  48810. this._uniformBuffer.addUniform("vLightData", 4);
  48811. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48812. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48813. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48814. this._uniformBuffer.addUniform("depthValues", 2);
  48815. this._uniformBuffer.create();
  48816. };
  48817. /**
  48818. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48819. * @param effect The effect to update
  48820. * @param lightIndex The index of the light in the effect to update
  48821. * @returns The directional light
  48822. */
  48823. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48824. if (this.computeTransformedInformation()) {
  48825. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48826. return this;
  48827. }
  48828. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48829. return this;
  48830. };
  48831. /**
  48832. * Gets the minZ used for shadow according to both the scene and the light.
  48833. *
  48834. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48835. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48836. * @param activeCamera The camera we are returning the min for
  48837. * @returns the depth min z
  48838. */
  48839. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48840. return 1;
  48841. };
  48842. /**
  48843. * Gets the maxZ used for shadow according to both the scene and the light.
  48844. *
  48845. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48846. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48847. * @param activeCamera The camera we are returning the max for
  48848. * @returns the depth max z
  48849. */
  48850. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48851. return 1;
  48852. };
  48853. __decorate([
  48854. BABYLON.serialize()
  48855. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48856. __decorate([
  48857. BABYLON.serialize()
  48858. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48859. __decorate([
  48860. BABYLON.serialize()
  48861. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48862. return DirectionalLight;
  48863. }(BABYLON.ShadowLight));
  48864. BABYLON.DirectionalLight = DirectionalLight;
  48865. })(BABYLON || (BABYLON = {}));
  48866. //# sourceMappingURL=babylon.directionalLight.js.map
  48867. var BABYLON;
  48868. (function (BABYLON) {
  48869. /**
  48870. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48871. * These values define a cone of light starting from the position, emitting toward the direction.
  48872. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48873. * and the exponent defines the speed of the decay of the light with distance (reach).
  48874. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48875. */
  48876. var SpotLight = /** @class */ (function (_super) {
  48877. __extends(SpotLight, _super);
  48878. /**
  48879. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48880. * It can cast shadows.
  48881. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48882. * @param name The light friendly name
  48883. * @param position The position of the spot light in the scene
  48884. * @param direction The direction of the light in the scene
  48885. * @param angle The cone angle of the light in Radians
  48886. * @param exponent The light decay speed with the distance from the emission spot
  48887. * @param scene The scene the lights belongs to
  48888. */
  48889. function SpotLight(name, position, direction, angle, exponent, scene) {
  48890. var _this = _super.call(this, name, scene) || this;
  48891. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48892. _this._projectionTextureLightNear = 1e-6;
  48893. _this._projectionTextureLightFar = 1000.0;
  48894. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48895. _this._projectionTextureViewLightDirty = true;
  48896. _this._projectionTextureProjectionLightDirty = true;
  48897. _this._projectionTextureDirty = true;
  48898. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48899. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48900. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48901. _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);
  48902. _this.position = position;
  48903. _this.direction = direction;
  48904. _this.angle = angle;
  48905. _this.exponent = exponent;
  48906. return _this;
  48907. }
  48908. Object.defineProperty(SpotLight.prototype, "angle", {
  48909. /**
  48910. * Gets the cone angle of the spot light in Radians.
  48911. */
  48912. get: function () {
  48913. return this._angle;
  48914. },
  48915. /**
  48916. * Sets the cone angle of the spot light in Radians.
  48917. */
  48918. set: function (value) {
  48919. this._angle = value;
  48920. this._projectionTextureProjectionLightDirty = true;
  48921. this.forceProjectionMatrixCompute();
  48922. },
  48923. enumerable: true,
  48924. configurable: true
  48925. });
  48926. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48927. /**
  48928. * Allows scaling the angle of the light for shadow generation only.
  48929. */
  48930. get: function () {
  48931. return this._shadowAngleScale;
  48932. },
  48933. /**
  48934. * Allows scaling the angle of the light for shadow generation only.
  48935. */
  48936. set: function (value) {
  48937. this._shadowAngleScale = value;
  48938. this.forceProjectionMatrixCompute();
  48939. },
  48940. enumerable: true,
  48941. configurable: true
  48942. });
  48943. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48944. /**
  48945. * Allows reading the projecton texture
  48946. */
  48947. get: function () {
  48948. return this._projectionTextureMatrix;
  48949. },
  48950. enumerable: true,
  48951. configurable: true
  48952. });
  48953. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48954. /**
  48955. * Gets the near clip of the Spotlight for texture projection.
  48956. */
  48957. get: function () {
  48958. return this._projectionTextureLightNear;
  48959. },
  48960. /**
  48961. * Sets the near clip of the Spotlight for texture projection.
  48962. */
  48963. set: function (value) {
  48964. this._projectionTextureLightNear = value;
  48965. this._projectionTextureProjectionLightDirty = true;
  48966. },
  48967. enumerable: true,
  48968. configurable: true
  48969. });
  48970. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48971. /**
  48972. * Gets the far clip of the Spotlight for texture projection.
  48973. */
  48974. get: function () {
  48975. return this._projectionTextureLightFar;
  48976. },
  48977. /**
  48978. * Sets the far clip of the Spotlight for texture projection.
  48979. */
  48980. set: function (value) {
  48981. this._projectionTextureLightFar = value;
  48982. this._projectionTextureProjectionLightDirty = true;
  48983. },
  48984. enumerable: true,
  48985. configurable: true
  48986. });
  48987. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48988. /**
  48989. * Gets the Up vector of the Spotlight for texture projection.
  48990. */
  48991. get: function () {
  48992. return this._projectionTextureUpDirection;
  48993. },
  48994. /**
  48995. * Sets the Up vector of the Spotlight for texture projection.
  48996. */
  48997. set: function (value) {
  48998. this._projectionTextureUpDirection = value;
  48999. this._projectionTextureProjectionLightDirty = true;
  49000. },
  49001. enumerable: true,
  49002. configurable: true
  49003. });
  49004. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49005. /**
  49006. * Gets the projection texture of the light.
  49007. */
  49008. get: function () {
  49009. return this._projectionTexture;
  49010. },
  49011. /**
  49012. * Sets the projection texture of the light.
  49013. */
  49014. set: function (value) {
  49015. this._projectionTexture = value;
  49016. this._projectionTextureDirty = true;
  49017. },
  49018. enumerable: true,
  49019. configurable: true
  49020. });
  49021. /**
  49022. * Returns the string "SpotLight".
  49023. * @returns the class name
  49024. */
  49025. SpotLight.prototype.getClassName = function () {
  49026. return "SpotLight";
  49027. };
  49028. /**
  49029. * Returns the integer 2.
  49030. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49031. */
  49032. SpotLight.prototype.getTypeID = function () {
  49033. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49034. };
  49035. /**
  49036. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49037. */
  49038. SpotLight.prototype._setDirection = function (value) {
  49039. _super.prototype._setDirection.call(this, value);
  49040. this._projectionTextureViewLightDirty = true;
  49041. };
  49042. /**
  49043. * Overrides the position setter to recompute the projection texture view light Matrix.
  49044. */
  49045. SpotLight.prototype._setPosition = function (value) {
  49046. _super.prototype._setPosition.call(this, value);
  49047. this._projectionTextureViewLightDirty = true;
  49048. };
  49049. /**
  49050. * 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.
  49051. * Returns the SpotLight.
  49052. */
  49053. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49054. var activeCamera = this.getScene().activeCamera;
  49055. if (!activeCamera) {
  49056. return;
  49057. }
  49058. this._shadowAngleScale = this._shadowAngleScale || 1;
  49059. var angle = this._shadowAngleScale * this._angle;
  49060. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49061. };
  49062. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49063. this._projectionTextureViewLightDirty = false;
  49064. this._projectionTextureDirty = true;
  49065. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49066. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49067. };
  49068. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49069. this._projectionTextureProjectionLightDirty = false;
  49070. this._projectionTextureDirty = true;
  49071. var light_far = this.projectionTextureLightFar;
  49072. var light_near = this.projectionTextureLightNear;
  49073. var P = light_far / (light_far - light_near);
  49074. var Q = -P * light_near;
  49075. var S = 1.0 / Math.tan(this._angle / 2.0);
  49076. var A = 1.0;
  49077. 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);
  49078. };
  49079. /**
  49080. * Main function for light texture projection matrix computing.
  49081. */
  49082. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49083. this._projectionTextureDirty = false;
  49084. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49085. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49086. };
  49087. SpotLight.prototype._buildUniformLayout = function () {
  49088. this._uniformBuffer.addUniform("vLightData", 4);
  49089. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49090. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49091. this._uniformBuffer.addUniform("vLightDirection", 3);
  49092. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49093. this._uniformBuffer.addUniform("depthValues", 2);
  49094. this._uniformBuffer.create();
  49095. };
  49096. /**
  49097. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49098. * @param effect The effect to update
  49099. * @param lightIndex The index of the light in the effect to update
  49100. * @returns The spot light
  49101. */
  49102. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49103. var normalizeDirection;
  49104. if (this.computeTransformedInformation()) {
  49105. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49106. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49107. }
  49108. else {
  49109. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49110. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49111. }
  49112. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49113. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49114. if (this._projectionTextureViewLightDirty) {
  49115. this._computeProjectionTextureViewLightMatrix();
  49116. }
  49117. if (this._projectionTextureProjectionLightDirty) {
  49118. this._computeProjectionTextureProjectionLightMatrix();
  49119. }
  49120. if (this._projectionTextureDirty) {
  49121. this._computeProjectionTextureMatrix();
  49122. }
  49123. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49124. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49125. }
  49126. return this;
  49127. };
  49128. /**
  49129. * Disposes the light and the associated resources.
  49130. */
  49131. SpotLight.prototype.dispose = function () {
  49132. _super.prototype.dispose.call(this);
  49133. if (this._projectionTexture) {
  49134. this._projectionTexture.dispose();
  49135. }
  49136. };
  49137. __decorate([
  49138. BABYLON.serialize()
  49139. ], SpotLight.prototype, "angle", null);
  49140. __decorate([
  49141. BABYLON.serialize()
  49142. ], SpotLight.prototype, "shadowAngleScale", null);
  49143. __decorate([
  49144. BABYLON.serialize()
  49145. ], SpotLight.prototype, "exponent", void 0);
  49146. __decorate([
  49147. BABYLON.serialize()
  49148. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49149. __decorate([
  49150. BABYLON.serialize()
  49151. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49152. __decorate([
  49153. BABYLON.serialize()
  49154. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49155. __decorate([
  49156. BABYLON.serializeAsTexture("projectedLightTexture")
  49157. ], SpotLight.prototype, "_projectionTexture", void 0);
  49158. return SpotLight;
  49159. }(BABYLON.ShadowLight));
  49160. BABYLON.SpotLight = SpotLight;
  49161. })(BABYLON || (BABYLON = {}));
  49162. //# sourceMappingURL=babylon.spotLight.js.map
  49163. var BABYLON;
  49164. (function (BABYLON) {
  49165. /**
  49166. * Class used to override all child animations of a given target
  49167. */
  49168. var AnimationPropertiesOverride = /** @class */ (function () {
  49169. function AnimationPropertiesOverride() {
  49170. /**
  49171. * Gets or sets a value indicating if animation blending must be used
  49172. */
  49173. this.enableBlending = false;
  49174. /**
  49175. * Gets or sets the blending speed to use when enableBlending is true
  49176. */
  49177. this.blendingSpeed = 0.01;
  49178. /**
  49179. * Gets or sets the default loop mode to use
  49180. */
  49181. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49182. }
  49183. return AnimationPropertiesOverride;
  49184. }());
  49185. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49186. })(BABYLON || (BABYLON = {}));
  49187. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49188. var BABYLON;
  49189. (function (BABYLON) {
  49190. /**
  49191. * Represents the range of an animation
  49192. */
  49193. var AnimationRange = /** @class */ (function () {
  49194. /**
  49195. * Initializes the range of an animation
  49196. * @param name The name of the animation range
  49197. * @param from The starting frame of the animation
  49198. * @param to The ending frame of the animation
  49199. */
  49200. function AnimationRange(
  49201. /**The name of the animation range**/
  49202. name,
  49203. /**The starting frame of the animation */
  49204. from,
  49205. /**The ending frame of the animation*/
  49206. to) {
  49207. this.name = name;
  49208. this.from = from;
  49209. this.to = to;
  49210. }
  49211. /**
  49212. * Makes a copy of the animation range
  49213. * @returns A copy of the animation range
  49214. */
  49215. AnimationRange.prototype.clone = function () {
  49216. return new AnimationRange(this.name, this.from, this.to);
  49217. };
  49218. return AnimationRange;
  49219. }());
  49220. BABYLON.AnimationRange = AnimationRange;
  49221. /**
  49222. * Composed of a frame, and an action function
  49223. */
  49224. var AnimationEvent = /** @class */ (function () {
  49225. /**
  49226. * Initializes the animation event
  49227. * @param frame The frame for which the event is triggered
  49228. * @param action The event to perform when triggered
  49229. * @param onlyOnce Specifies if the event should be triggered only once
  49230. */
  49231. function AnimationEvent(
  49232. /** The frame for which the event is triggered **/
  49233. frame,
  49234. /** The event to perform when triggered **/
  49235. action,
  49236. /** Specifies if the event should be triggered only once**/
  49237. onlyOnce) {
  49238. this.frame = frame;
  49239. this.action = action;
  49240. this.onlyOnce = onlyOnce;
  49241. /**
  49242. * Specifies if the animation event is done
  49243. */
  49244. this.isDone = false;
  49245. }
  49246. /** @hidden */
  49247. AnimationEvent.prototype._clone = function () {
  49248. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49249. };
  49250. return AnimationEvent;
  49251. }());
  49252. BABYLON.AnimationEvent = AnimationEvent;
  49253. /**
  49254. * A cursor which tracks a point on a path
  49255. */
  49256. var PathCursor = /** @class */ (function () {
  49257. /**
  49258. * Initializes the path cursor
  49259. * @param path The path to track
  49260. */
  49261. function PathCursor(path) {
  49262. this.path = path;
  49263. /**
  49264. * Stores path cursor callbacks for when an onchange event is triggered
  49265. */
  49266. this._onchange = new Array();
  49267. /**
  49268. * The value of the path cursor
  49269. */
  49270. this.value = 0;
  49271. /**
  49272. * The animation array of the path cursor
  49273. */
  49274. this.animations = new Array();
  49275. }
  49276. /**
  49277. * Gets the cursor point on the path
  49278. * @returns A point on the path cursor at the cursor location
  49279. */
  49280. PathCursor.prototype.getPoint = function () {
  49281. var point = this.path.getPointAtLengthPosition(this.value);
  49282. return new BABYLON.Vector3(point.x, 0, point.y);
  49283. };
  49284. /**
  49285. * Moves the cursor ahead by the step amount
  49286. * @param step The amount to move the cursor forward
  49287. * @returns This path cursor
  49288. */
  49289. PathCursor.prototype.moveAhead = function (step) {
  49290. if (step === void 0) { step = 0.002; }
  49291. this.move(step);
  49292. return this;
  49293. };
  49294. /**
  49295. * Moves the cursor behind by the step amount
  49296. * @param step The amount to move the cursor back
  49297. * @returns This path cursor
  49298. */
  49299. PathCursor.prototype.moveBack = function (step) {
  49300. if (step === void 0) { step = 0.002; }
  49301. this.move(-step);
  49302. return this;
  49303. };
  49304. /**
  49305. * Moves the cursor by the step amount
  49306. * If the step amount is greater than one, an exception is thrown
  49307. * @param step The amount to move the cursor
  49308. * @returns This path cursor
  49309. */
  49310. PathCursor.prototype.move = function (step) {
  49311. if (Math.abs(step) > 1) {
  49312. throw "step size should be less than 1.";
  49313. }
  49314. this.value += step;
  49315. this.ensureLimits();
  49316. this.raiseOnChange();
  49317. return this;
  49318. };
  49319. /**
  49320. * Ensures that the value is limited between zero and one
  49321. * @returns This path cursor
  49322. */
  49323. PathCursor.prototype.ensureLimits = function () {
  49324. while (this.value > 1) {
  49325. this.value -= 1;
  49326. }
  49327. while (this.value < 0) {
  49328. this.value += 1;
  49329. }
  49330. return this;
  49331. };
  49332. /**
  49333. * Runs onchange callbacks on change (used by the animation engine)
  49334. * @returns This path cursor
  49335. */
  49336. PathCursor.prototype.raiseOnChange = function () {
  49337. var _this = this;
  49338. this._onchange.forEach(function (f) { return f(_this); });
  49339. return this;
  49340. };
  49341. /**
  49342. * Executes a function on change
  49343. * @param f A path cursor onchange callback
  49344. * @returns This path cursor
  49345. */
  49346. PathCursor.prototype.onchange = function (f) {
  49347. this._onchange.push(f);
  49348. return this;
  49349. };
  49350. return PathCursor;
  49351. }());
  49352. BABYLON.PathCursor = PathCursor;
  49353. /**
  49354. * Enum for the animation key frame interpolation type
  49355. */
  49356. var AnimationKeyInterpolation;
  49357. (function (AnimationKeyInterpolation) {
  49358. /**
  49359. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49360. */
  49361. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49362. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49363. /**
  49364. * Class used to store any kind of animation
  49365. */
  49366. var Animation = /** @class */ (function () {
  49367. /**
  49368. * Initializes the animation
  49369. * @param name Name of the animation
  49370. * @param targetProperty Property to animate
  49371. * @param framePerSecond The frames per second of the animation
  49372. * @param dataType The data type of the animation
  49373. * @param loopMode The loop mode of the animation
  49374. * @param enableBlendings Specifies if blending should be enabled
  49375. */
  49376. function Animation(
  49377. /**Name of the animation */
  49378. name,
  49379. /**Property to animate */
  49380. targetProperty,
  49381. /**The frames per second of the animation */
  49382. framePerSecond,
  49383. /**The data type of the animation */
  49384. dataType,
  49385. /**The loop mode of the animation */
  49386. loopMode,
  49387. /**Specifies if blending should be enabled */
  49388. enableBlending) {
  49389. this.name = name;
  49390. this.targetProperty = targetProperty;
  49391. this.framePerSecond = framePerSecond;
  49392. this.dataType = dataType;
  49393. this.loopMode = loopMode;
  49394. this.enableBlending = enableBlending;
  49395. /**
  49396. * @hidden Internal use only
  49397. */
  49398. this._runtimeAnimations = new Array();
  49399. /**
  49400. * The set of event that will be linked to this animation
  49401. */
  49402. this._events = new Array();
  49403. /**
  49404. * Stores the blending speed of the animation
  49405. */
  49406. this.blendingSpeed = 0.01;
  49407. /**
  49408. * Stores the animation ranges for the animation
  49409. */
  49410. this._ranges = {};
  49411. this.targetPropertyPath = targetProperty.split(".");
  49412. this.dataType = dataType;
  49413. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49414. }
  49415. /**
  49416. * @hidden Internal use
  49417. */
  49418. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49419. var dataType = undefined;
  49420. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49421. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49422. }
  49423. else if (from instanceof BABYLON.Quaternion) {
  49424. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49425. }
  49426. else if (from instanceof BABYLON.Vector3) {
  49427. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49428. }
  49429. else if (from instanceof BABYLON.Vector2) {
  49430. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49431. }
  49432. else if (from instanceof BABYLON.Color3) {
  49433. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49434. }
  49435. else if (from instanceof BABYLON.Size) {
  49436. dataType = Animation.ANIMATIONTYPE_SIZE;
  49437. }
  49438. if (dataType == undefined) {
  49439. return null;
  49440. }
  49441. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49442. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49443. animation.setKeys(keys);
  49444. if (easingFunction !== undefined) {
  49445. animation.setEasingFunction(easingFunction);
  49446. }
  49447. return animation;
  49448. };
  49449. /**
  49450. * Sets up an animation
  49451. * @param property The property to animate
  49452. * @param animationType The animation type to apply
  49453. * @param framePerSecond The frames per second of the animation
  49454. * @param easingFunction The easing function used in the animation
  49455. * @returns The created animation
  49456. */
  49457. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49458. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49459. animation.setEasingFunction(easingFunction);
  49460. return animation;
  49461. };
  49462. /**
  49463. * Create and start an animation on a node
  49464. * @param name defines the name of the global animation that will be run on all nodes
  49465. * @param node defines the root node where the animation will take place
  49466. * @param targetProperty defines property to animate
  49467. * @param framePerSecond defines the number of frame per second yo use
  49468. * @param totalFrame defines the number of frames in total
  49469. * @param from defines the initial value
  49470. * @param to defines the final value
  49471. * @param loopMode defines which loop mode you want to use (off by default)
  49472. * @param easingFunction defines the easing function to use (linear by default)
  49473. * @param onAnimationEnd defines the callback to call when animation end
  49474. * @returns the animatable created for this animation
  49475. */
  49476. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49477. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49478. if (!animation) {
  49479. return null;
  49480. }
  49481. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49482. };
  49483. /**
  49484. * Create and start an animation on a node and its descendants
  49485. * @param name defines the name of the global animation that will be run on all nodes
  49486. * @param node defines the root node where the animation will take place
  49487. * @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
  49488. * @param targetProperty defines property to animate
  49489. * @param framePerSecond defines the number of frame per second to use
  49490. * @param totalFrame defines the number of frames in total
  49491. * @param from defines the initial value
  49492. * @param to defines the final value
  49493. * @param loopMode defines which loop mode you want to use (off by default)
  49494. * @param easingFunction defines the easing function to use (linear by default)
  49495. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49496. * @returns the list of animatables created for all nodes
  49497. * @example https://www.babylonjs-playground.com/#MH0VLI
  49498. */
  49499. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49500. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49501. if (!animation) {
  49502. return null;
  49503. }
  49504. var scene = node.getScene();
  49505. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49506. };
  49507. /**
  49508. * Creates a new animation, merges it with the existing animations and starts it
  49509. * @param name Name of the animation
  49510. * @param node Node which contains the scene that begins the animations
  49511. * @param targetProperty Specifies which property to animate
  49512. * @param framePerSecond The frames per second of the animation
  49513. * @param totalFrame The total number of frames
  49514. * @param from The frame at the beginning of the animation
  49515. * @param to The frame at the end of the animation
  49516. * @param loopMode Specifies the loop mode of the animation
  49517. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49518. * @param onAnimationEnd Callback to run once the animation is complete
  49519. * @returns Nullable animation
  49520. */
  49521. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49522. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49523. if (!animation) {
  49524. return null;
  49525. }
  49526. node.animations.push(animation);
  49527. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49528. };
  49529. /**
  49530. * Transition property of an host to the target Value
  49531. * @param property The property to transition
  49532. * @param targetValue The target Value of the property
  49533. * @param host The object where the property to animate belongs
  49534. * @param scene Scene used to run the animation
  49535. * @param frameRate Framerate (in frame/s) to use
  49536. * @param transition The transition type we want to use
  49537. * @param duration The duration of the animation, in milliseconds
  49538. * @param onAnimationEnd Callback trigger at the end of the animation
  49539. * @returns Nullable animation
  49540. */
  49541. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49542. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49543. if (duration <= 0) {
  49544. host[property] = targetValue;
  49545. if (onAnimationEnd) {
  49546. onAnimationEnd();
  49547. }
  49548. return null;
  49549. }
  49550. var endFrame = frameRate * (duration / 1000);
  49551. transition.setKeys([{
  49552. frame: 0,
  49553. value: host[property].clone ? host[property].clone() : host[property]
  49554. },
  49555. {
  49556. frame: endFrame,
  49557. value: targetValue
  49558. }]);
  49559. if (!host.animations) {
  49560. host.animations = [];
  49561. }
  49562. host.animations.push(transition);
  49563. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49564. animation.onAnimationEnd = onAnimationEnd;
  49565. return animation;
  49566. };
  49567. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49568. /**
  49569. * Return the array of runtime animations currently using this animation
  49570. */
  49571. get: function () {
  49572. return this._runtimeAnimations;
  49573. },
  49574. enumerable: true,
  49575. configurable: true
  49576. });
  49577. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49578. /**
  49579. * Specifies if any of the runtime animations are currently running
  49580. */
  49581. get: function () {
  49582. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49583. var runtimeAnimation = _a[_i];
  49584. if (!runtimeAnimation.isStopped) {
  49585. return true;
  49586. }
  49587. }
  49588. return false;
  49589. },
  49590. enumerable: true,
  49591. configurable: true
  49592. });
  49593. // Methods
  49594. /**
  49595. * Converts the animation to a string
  49596. * @param fullDetails support for multiple levels of logging within scene loading
  49597. * @returns String form of the animation
  49598. */
  49599. Animation.prototype.toString = function (fullDetails) {
  49600. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49601. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49602. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49603. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49604. if (fullDetails) {
  49605. ret += ", Ranges: {";
  49606. var first = true;
  49607. for (var name in this._ranges) {
  49608. if (first) {
  49609. ret += ", ";
  49610. first = false;
  49611. }
  49612. ret += name;
  49613. }
  49614. ret += "}";
  49615. }
  49616. return ret;
  49617. };
  49618. /**
  49619. * Add an event to this animation
  49620. * @param event Event to add
  49621. */
  49622. Animation.prototype.addEvent = function (event) {
  49623. this._events.push(event);
  49624. };
  49625. /**
  49626. * Remove all events found at the given frame
  49627. * @param frame The frame to remove events from
  49628. */
  49629. Animation.prototype.removeEvents = function (frame) {
  49630. for (var index = 0; index < this._events.length; index++) {
  49631. if (this._events[index].frame === frame) {
  49632. this._events.splice(index, 1);
  49633. index--;
  49634. }
  49635. }
  49636. };
  49637. /**
  49638. * Retrieves all the events from the animation
  49639. * @returns Events from the animation
  49640. */
  49641. Animation.prototype.getEvents = function () {
  49642. return this._events;
  49643. };
  49644. /**
  49645. * Creates an animation range
  49646. * @param name Name of the animation range
  49647. * @param from Starting frame of the animation range
  49648. * @param to Ending frame of the animation
  49649. */
  49650. Animation.prototype.createRange = function (name, from, to) {
  49651. // check name not already in use; could happen for bones after serialized
  49652. if (!this._ranges[name]) {
  49653. this._ranges[name] = new AnimationRange(name, from, to);
  49654. }
  49655. };
  49656. /**
  49657. * Deletes an animation range by name
  49658. * @param name Name of the animation range to delete
  49659. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49660. */
  49661. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49662. if (deleteFrames === void 0) { deleteFrames = true; }
  49663. var range = this._ranges[name];
  49664. if (!range) {
  49665. return;
  49666. }
  49667. if (deleteFrames) {
  49668. var from = range.from;
  49669. var to = range.to;
  49670. // this loop MUST go high to low for multiple splices to work
  49671. for (var key = this._keys.length - 1; key >= 0; key--) {
  49672. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49673. this._keys.splice(key, 1);
  49674. }
  49675. }
  49676. }
  49677. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49678. };
  49679. /**
  49680. * Gets the animation range by name, or null if not defined
  49681. * @param name Name of the animation range
  49682. * @returns Nullable animation range
  49683. */
  49684. Animation.prototype.getRange = function (name) {
  49685. return this._ranges[name];
  49686. };
  49687. /**
  49688. * Gets the key frames from the animation
  49689. * @returns The key frames of the animation
  49690. */
  49691. Animation.prototype.getKeys = function () {
  49692. return this._keys;
  49693. };
  49694. /**
  49695. * Gets the highest frame rate of the animation
  49696. * @returns Highest frame rate of the animation
  49697. */
  49698. Animation.prototype.getHighestFrame = function () {
  49699. var ret = 0;
  49700. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49701. if (ret < this._keys[key].frame) {
  49702. ret = this._keys[key].frame;
  49703. }
  49704. }
  49705. return ret;
  49706. };
  49707. /**
  49708. * Gets the easing function of the animation
  49709. * @returns Easing function of the animation
  49710. */
  49711. Animation.prototype.getEasingFunction = function () {
  49712. return this._easingFunction;
  49713. };
  49714. /**
  49715. * Sets the easing function of the animation
  49716. * @param easingFunction A custom mathematical formula for animation
  49717. */
  49718. Animation.prototype.setEasingFunction = function (easingFunction) {
  49719. this._easingFunction = easingFunction;
  49720. };
  49721. /**
  49722. * Interpolates a scalar linearly
  49723. * @param startValue Start value of the animation curve
  49724. * @param endValue End value of the animation curve
  49725. * @param gradient Scalar amount to interpolate
  49726. * @returns Interpolated scalar value
  49727. */
  49728. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49729. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49730. };
  49731. /**
  49732. * Interpolates a scalar cubically
  49733. * @param startValue Start value of the animation curve
  49734. * @param outTangent End tangent of the animation
  49735. * @param endValue End value of the animation curve
  49736. * @param inTangent Start tangent of the animation curve
  49737. * @param gradient Scalar amount to interpolate
  49738. * @returns Interpolated scalar value
  49739. */
  49740. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49741. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49742. };
  49743. /**
  49744. * Interpolates a quaternion using a spherical linear interpolation
  49745. * @param startValue Start value of the animation curve
  49746. * @param endValue End value of the animation curve
  49747. * @param gradient Scalar amount to interpolate
  49748. * @returns Interpolated quaternion value
  49749. */
  49750. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49751. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49752. };
  49753. /**
  49754. * Interpolates a quaternion cubically
  49755. * @param startValue Start value of the animation curve
  49756. * @param outTangent End tangent of the animation curve
  49757. * @param endValue End value of the animation curve
  49758. * @param inTangent Start tangent of the animation curve
  49759. * @param gradient Scalar amount to interpolate
  49760. * @returns Interpolated quaternion value
  49761. */
  49762. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49763. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49764. };
  49765. /**
  49766. * Interpolates a Vector3 linearl
  49767. * @param startValue Start value of the animation curve
  49768. * @param endValue End value of the animation curve
  49769. * @param gradient Scalar amount to interpolate
  49770. * @returns Interpolated scalar value
  49771. */
  49772. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49773. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49774. };
  49775. /**
  49776. * Interpolates a Vector3 cubically
  49777. * @param startValue Start value of the animation curve
  49778. * @param outTangent End tangent of the animation
  49779. * @param endValue End value of the animation curve
  49780. * @param inTangent Start tangent of the animation curve
  49781. * @param gradient Scalar amount to interpolate
  49782. * @returns InterpolatedVector3 value
  49783. */
  49784. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49785. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49786. };
  49787. /**
  49788. * Interpolates a Vector2 linearly
  49789. * @param startValue Start value of the animation curve
  49790. * @param endValue End value of the animation curve
  49791. * @param gradient Scalar amount to interpolate
  49792. * @returns Interpolated Vector2 value
  49793. */
  49794. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49795. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49796. };
  49797. /**
  49798. * Interpolates a Vector2 cubically
  49799. * @param startValue Start value of the animation curve
  49800. * @param outTangent End tangent of the animation
  49801. * @param endValue End value of the animation curve
  49802. * @param inTangent Start tangent of the animation curve
  49803. * @param gradient Scalar amount to interpolate
  49804. * @returns Interpolated Vector2 value
  49805. */
  49806. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49807. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49808. };
  49809. /**
  49810. * Interpolates a size linearly
  49811. * @param startValue Start value of the animation curve
  49812. * @param endValue End value of the animation curve
  49813. * @param gradient Scalar amount to interpolate
  49814. * @returns Interpolated Size value
  49815. */
  49816. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49817. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49818. };
  49819. /**
  49820. * Interpolates a Color3 linearly
  49821. * @param startValue Start value of the animation curve
  49822. * @param endValue End value of the animation curve
  49823. * @param gradient Scalar amount to interpolate
  49824. * @returns Interpolated Color3 value
  49825. */
  49826. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49827. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49828. };
  49829. /**
  49830. * @hidden Internal use only
  49831. */
  49832. Animation.prototype._getKeyValue = function (value) {
  49833. if (typeof value === "function") {
  49834. return value();
  49835. }
  49836. return value;
  49837. };
  49838. /**
  49839. * @hidden Internal use only
  49840. */
  49841. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49842. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49843. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49844. }
  49845. var keys = this.getKeys();
  49846. // Try to get a hash to find the right key
  49847. 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));
  49848. if (keys[startKeyIndex].frame >= currentFrame) {
  49849. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49850. startKeyIndex--;
  49851. }
  49852. }
  49853. for (var key = startKeyIndex; key < keys.length; key++) {
  49854. var endKey = keys[key + 1];
  49855. if (endKey.frame >= currentFrame) {
  49856. var startKey = keys[key];
  49857. var startValue = this._getKeyValue(startKey.value);
  49858. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49859. return startValue;
  49860. }
  49861. var endValue = this._getKeyValue(endKey.value);
  49862. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49863. var frameDelta = endKey.frame - startKey.frame;
  49864. // gradient : percent of currentFrame between the frame inf and the frame sup
  49865. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49866. // check for easingFunction and correction of gradient
  49867. var easingFunction = this.getEasingFunction();
  49868. if (easingFunction != null) {
  49869. gradient = easingFunction.ease(gradient);
  49870. }
  49871. switch (this.dataType) {
  49872. // Float
  49873. case Animation.ANIMATIONTYPE_FLOAT:
  49874. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49875. switch (loopMode) {
  49876. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49877. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49878. return floatValue;
  49879. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49880. return offsetValue * repeatCount + floatValue;
  49881. }
  49882. break;
  49883. // Quaternion
  49884. case Animation.ANIMATIONTYPE_QUATERNION:
  49885. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49886. switch (loopMode) {
  49887. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49888. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49889. return quatValue;
  49890. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49891. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49892. }
  49893. return quatValue;
  49894. // Vector3
  49895. case Animation.ANIMATIONTYPE_VECTOR3:
  49896. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49897. switch (loopMode) {
  49898. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49899. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49900. return vec3Value;
  49901. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49902. return vec3Value.add(offsetValue.scale(repeatCount));
  49903. }
  49904. // Vector2
  49905. case Animation.ANIMATIONTYPE_VECTOR2:
  49906. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49907. switch (loopMode) {
  49908. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49909. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49910. return vec2Value;
  49911. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49912. return vec2Value.add(offsetValue.scale(repeatCount));
  49913. }
  49914. // Size
  49915. case Animation.ANIMATIONTYPE_SIZE:
  49916. switch (loopMode) {
  49917. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49918. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49919. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49920. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49921. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49922. }
  49923. // Color3
  49924. case Animation.ANIMATIONTYPE_COLOR3:
  49925. switch (loopMode) {
  49926. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49927. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49928. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49929. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49930. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49931. }
  49932. // Matrix
  49933. case Animation.ANIMATIONTYPE_MATRIX:
  49934. switch (loopMode) {
  49935. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49936. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49937. if (Animation.AllowMatricesInterpolation) {
  49938. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49939. }
  49940. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49941. return startValue;
  49942. }
  49943. default:
  49944. break;
  49945. }
  49946. break;
  49947. }
  49948. }
  49949. return this._getKeyValue(keys[keys.length - 1].value);
  49950. };
  49951. /**
  49952. * Defines the function to use to interpolate matrices
  49953. * @param startValue defines the start matrix
  49954. * @param endValue defines the end matrix
  49955. * @param gradient defines the gradient between both matrices
  49956. * @param result defines an optional target matrix where to store the interpolation
  49957. * @returns the interpolated matrix
  49958. */
  49959. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49960. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49961. if (result) {
  49962. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49963. return result;
  49964. }
  49965. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49966. }
  49967. if (result) {
  49968. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49969. return result;
  49970. }
  49971. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49972. };
  49973. /**
  49974. * Makes a copy of the animation
  49975. * @returns Cloned animation
  49976. */
  49977. Animation.prototype.clone = function () {
  49978. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49979. clone.enableBlending = this.enableBlending;
  49980. clone.blendingSpeed = this.blendingSpeed;
  49981. if (this._keys) {
  49982. clone.setKeys(this._keys);
  49983. }
  49984. if (this._ranges) {
  49985. clone._ranges = {};
  49986. for (var name in this._ranges) {
  49987. var range = this._ranges[name];
  49988. if (!range) {
  49989. continue;
  49990. }
  49991. clone._ranges[name] = range.clone();
  49992. }
  49993. }
  49994. return clone;
  49995. };
  49996. /**
  49997. * Sets the key frames of the animation
  49998. * @param values The animation key frames to set
  49999. */
  50000. Animation.prototype.setKeys = function (values) {
  50001. this._keys = values.slice(0);
  50002. };
  50003. /**
  50004. * Serializes the animation to an object
  50005. * @returns Serialized object
  50006. */
  50007. Animation.prototype.serialize = function () {
  50008. var serializationObject = {};
  50009. serializationObject.name = this.name;
  50010. serializationObject.property = this.targetProperty;
  50011. serializationObject.framePerSecond = this.framePerSecond;
  50012. serializationObject.dataType = this.dataType;
  50013. serializationObject.loopBehavior = this.loopMode;
  50014. serializationObject.enableBlending = this.enableBlending;
  50015. serializationObject.blendingSpeed = this.blendingSpeed;
  50016. var dataType = this.dataType;
  50017. serializationObject.keys = [];
  50018. var keys = this.getKeys();
  50019. for (var index = 0; index < keys.length; index++) {
  50020. var animationKey = keys[index];
  50021. var key = {};
  50022. key.frame = animationKey.frame;
  50023. switch (dataType) {
  50024. case Animation.ANIMATIONTYPE_FLOAT:
  50025. key.values = [animationKey.value];
  50026. break;
  50027. case Animation.ANIMATIONTYPE_QUATERNION:
  50028. case Animation.ANIMATIONTYPE_MATRIX:
  50029. case Animation.ANIMATIONTYPE_VECTOR3:
  50030. case Animation.ANIMATIONTYPE_COLOR3:
  50031. key.values = animationKey.value.asArray();
  50032. break;
  50033. }
  50034. serializationObject.keys.push(key);
  50035. }
  50036. serializationObject.ranges = [];
  50037. for (var name in this._ranges) {
  50038. var source = this._ranges[name];
  50039. if (!source) {
  50040. continue;
  50041. }
  50042. var range = {};
  50043. range.name = name;
  50044. range.from = source.from;
  50045. range.to = source.to;
  50046. serializationObject.ranges.push(range);
  50047. }
  50048. return serializationObject;
  50049. };
  50050. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50051. /**
  50052. * Get the float animation type
  50053. */
  50054. get: function () {
  50055. return Animation._ANIMATIONTYPE_FLOAT;
  50056. },
  50057. enumerable: true,
  50058. configurable: true
  50059. });
  50060. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50061. /**
  50062. * Get the Vector3 animation type
  50063. */
  50064. get: function () {
  50065. return Animation._ANIMATIONTYPE_VECTOR3;
  50066. },
  50067. enumerable: true,
  50068. configurable: true
  50069. });
  50070. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50071. /**
  50072. * Get the Vectpr2 animation type
  50073. */
  50074. get: function () {
  50075. return Animation._ANIMATIONTYPE_VECTOR2;
  50076. },
  50077. enumerable: true,
  50078. configurable: true
  50079. });
  50080. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50081. /**
  50082. * Get the Size animation type
  50083. */
  50084. get: function () {
  50085. return Animation._ANIMATIONTYPE_SIZE;
  50086. },
  50087. enumerable: true,
  50088. configurable: true
  50089. });
  50090. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50091. /**
  50092. * Get the Quaternion animation type
  50093. */
  50094. get: function () {
  50095. return Animation._ANIMATIONTYPE_QUATERNION;
  50096. },
  50097. enumerable: true,
  50098. configurable: true
  50099. });
  50100. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50101. /**
  50102. * Get the Matrix animation type
  50103. */
  50104. get: function () {
  50105. return Animation._ANIMATIONTYPE_MATRIX;
  50106. },
  50107. enumerable: true,
  50108. configurable: true
  50109. });
  50110. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50111. /**
  50112. * Get the Color3 animation type
  50113. */
  50114. get: function () {
  50115. return Animation._ANIMATIONTYPE_COLOR3;
  50116. },
  50117. enumerable: true,
  50118. configurable: true
  50119. });
  50120. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50121. /**
  50122. * Get the Relative Loop Mode
  50123. */
  50124. get: function () {
  50125. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50126. },
  50127. enumerable: true,
  50128. configurable: true
  50129. });
  50130. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50131. /**
  50132. * Get the Cycle Loop Mode
  50133. */
  50134. get: function () {
  50135. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50136. },
  50137. enumerable: true,
  50138. configurable: true
  50139. });
  50140. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50141. /**
  50142. * Get the Constant Loop Mode
  50143. */
  50144. get: function () {
  50145. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50146. },
  50147. enumerable: true,
  50148. configurable: true
  50149. });
  50150. /** @hidden */
  50151. Animation._UniversalLerp = function (left, right, amount) {
  50152. var constructor = left.constructor;
  50153. if (constructor.Lerp) { // Lerp supported
  50154. return constructor.Lerp(left, right, amount);
  50155. }
  50156. else if (constructor.Slerp) { // Slerp supported
  50157. return constructor.Slerp(left, right, amount);
  50158. }
  50159. else if (left.toFixed) { // Number
  50160. return left * (1.0 - amount) + amount * right;
  50161. }
  50162. else { // Blending not supported
  50163. return right;
  50164. }
  50165. };
  50166. /**
  50167. * Parses an animation object and creates an animation
  50168. * @param parsedAnimation Parsed animation object
  50169. * @returns Animation object
  50170. */
  50171. Animation.Parse = function (parsedAnimation) {
  50172. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50173. var dataType = parsedAnimation.dataType;
  50174. var keys = [];
  50175. var data;
  50176. var index;
  50177. if (parsedAnimation.enableBlending) {
  50178. animation.enableBlending = parsedAnimation.enableBlending;
  50179. }
  50180. if (parsedAnimation.blendingSpeed) {
  50181. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50182. }
  50183. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50184. var key = parsedAnimation.keys[index];
  50185. var inTangent;
  50186. var outTangent;
  50187. switch (dataType) {
  50188. case Animation.ANIMATIONTYPE_FLOAT:
  50189. data = key.values[0];
  50190. if (key.values.length >= 1) {
  50191. inTangent = key.values[1];
  50192. }
  50193. if (key.values.length >= 2) {
  50194. outTangent = key.values[2];
  50195. }
  50196. break;
  50197. case Animation.ANIMATIONTYPE_QUATERNION:
  50198. data = BABYLON.Quaternion.FromArray(key.values);
  50199. if (key.values.length >= 8) {
  50200. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50201. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50202. inTangent = _inTangent;
  50203. }
  50204. }
  50205. if (key.values.length >= 12) {
  50206. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50207. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50208. outTangent = _outTangent;
  50209. }
  50210. }
  50211. break;
  50212. case Animation.ANIMATIONTYPE_MATRIX:
  50213. data = BABYLON.Matrix.FromArray(key.values);
  50214. break;
  50215. case Animation.ANIMATIONTYPE_COLOR3:
  50216. data = BABYLON.Color3.FromArray(key.values);
  50217. break;
  50218. case Animation.ANIMATIONTYPE_VECTOR3:
  50219. default:
  50220. data = BABYLON.Vector3.FromArray(key.values);
  50221. break;
  50222. }
  50223. var keyData = {};
  50224. keyData.frame = key.frame;
  50225. keyData.value = data;
  50226. if (inTangent != undefined) {
  50227. keyData.inTangent = inTangent;
  50228. }
  50229. if (outTangent != undefined) {
  50230. keyData.outTangent = outTangent;
  50231. }
  50232. keys.push(keyData);
  50233. }
  50234. animation.setKeys(keys);
  50235. if (parsedAnimation.ranges) {
  50236. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50237. data = parsedAnimation.ranges[index];
  50238. animation.createRange(data.name, data.from, data.to);
  50239. }
  50240. }
  50241. return animation;
  50242. };
  50243. /**
  50244. * Appends the serialized animations from the source animations
  50245. * @param source Source containing the animations
  50246. * @param destination Target to store the animations
  50247. */
  50248. Animation.AppendSerializedAnimations = function (source, destination) {
  50249. if (source.animations) {
  50250. destination.animations = [];
  50251. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50252. var animation = source.animations[animationIndex];
  50253. destination.animations.push(animation.serialize());
  50254. }
  50255. }
  50256. };
  50257. /**
  50258. * Use matrix interpolation instead of using direct key value when animating matrices
  50259. */
  50260. Animation.AllowMatricesInterpolation = false;
  50261. /**
  50262. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50263. */
  50264. Animation.AllowMatrixDecomposeForInterpolation = true;
  50265. // Statics
  50266. /**
  50267. * Float animation type
  50268. */
  50269. Animation._ANIMATIONTYPE_FLOAT = 0;
  50270. /**
  50271. * Vector3 animation type
  50272. */
  50273. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50274. /**
  50275. * Quaternion animation type
  50276. */
  50277. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50278. /**
  50279. * Matrix animation type
  50280. */
  50281. Animation._ANIMATIONTYPE_MATRIX = 3;
  50282. /**
  50283. * Color3 animation type
  50284. */
  50285. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50286. /**
  50287. * Vector2 animation type
  50288. */
  50289. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50290. /**
  50291. * Size animation type
  50292. */
  50293. Animation._ANIMATIONTYPE_SIZE = 6;
  50294. /**
  50295. * Relative Loop Mode
  50296. */
  50297. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50298. /**
  50299. * Cycle Loop Mode
  50300. */
  50301. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50302. /**
  50303. * Constant Loop Mode
  50304. */
  50305. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50306. return Animation;
  50307. }());
  50308. BABYLON.Animation = Animation;
  50309. })(BABYLON || (BABYLON = {}));
  50310. //# sourceMappingURL=babylon.animation.js.map
  50311. var BABYLON;
  50312. (function (BABYLON) {
  50313. /**
  50314. * This class defines the direct association between an animation and a target
  50315. */
  50316. var TargetedAnimation = /** @class */ (function () {
  50317. function TargetedAnimation() {
  50318. }
  50319. return TargetedAnimation;
  50320. }());
  50321. BABYLON.TargetedAnimation = TargetedAnimation;
  50322. /**
  50323. * Use this class to create coordinated animations on multiple targets
  50324. */
  50325. var AnimationGroup = /** @class */ (function () {
  50326. function AnimationGroup(name, scene) {
  50327. if (scene === void 0) { scene = null; }
  50328. this.name = name;
  50329. this._targetedAnimations = new Array();
  50330. this._animatables = new Array();
  50331. this._from = Number.MAX_VALUE;
  50332. this._to = -Number.MAX_VALUE;
  50333. this._speedRatio = 1;
  50334. this.onAnimationEndObservable = new BABYLON.Observable();
  50335. /**
  50336. * This observable will notify when all animations have ended.
  50337. */
  50338. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50339. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50340. this._scene.animationGroups.push(this);
  50341. }
  50342. Object.defineProperty(AnimationGroup.prototype, "from", {
  50343. /**
  50344. * Gets the first frame
  50345. */
  50346. get: function () {
  50347. return this._from;
  50348. },
  50349. enumerable: true,
  50350. configurable: true
  50351. });
  50352. Object.defineProperty(AnimationGroup.prototype, "to", {
  50353. /**
  50354. * Gets the last frame
  50355. */
  50356. get: function () {
  50357. return this._to;
  50358. },
  50359. enumerable: true,
  50360. configurable: true
  50361. });
  50362. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50363. /**
  50364. * Define if the animations are started
  50365. */
  50366. get: function () {
  50367. return this._isStarted;
  50368. },
  50369. enumerable: true,
  50370. configurable: true
  50371. });
  50372. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50373. /**
  50374. * Gets or sets the speed ratio to use for all animations
  50375. */
  50376. get: function () {
  50377. return this._speedRatio;
  50378. },
  50379. /**
  50380. * Gets or sets the speed ratio to use for all animations
  50381. */
  50382. set: function (value) {
  50383. if (this._speedRatio === value) {
  50384. return;
  50385. }
  50386. this._speedRatio = value;
  50387. for (var index = 0; index < this._animatables.length; index++) {
  50388. var animatable = this._animatables[index];
  50389. animatable.speedRatio = this._speedRatio;
  50390. }
  50391. },
  50392. enumerable: true,
  50393. configurable: true
  50394. });
  50395. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50396. /**
  50397. * Gets the targeted animations for this animation group
  50398. */
  50399. get: function () {
  50400. return this._targetedAnimations;
  50401. },
  50402. enumerable: true,
  50403. configurable: true
  50404. });
  50405. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50406. /**
  50407. * returning the list of animatables controlled by this animation group.
  50408. */
  50409. get: function () {
  50410. return this._animatables;
  50411. },
  50412. enumerable: true,
  50413. configurable: true
  50414. });
  50415. /**
  50416. * Add an animation (with its target) in the group
  50417. * @param animation defines the animation we want to add
  50418. * @param target defines the target of the animation
  50419. * @returns the {BABYLON.TargetedAnimation} object
  50420. */
  50421. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50422. var targetedAnimation = {
  50423. animation: animation,
  50424. target: target
  50425. };
  50426. var keys = animation.getKeys();
  50427. if (this._from > keys[0].frame) {
  50428. this._from = keys[0].frame;
  50429. }
  50430. if (this._to < keys[keys.length - 1].frame) {
  50431. this._to = keys[keys.length - 1].frame;
  50432. }
  50433. this._targetedAnimations.push(targetedAnimation);
  50434. return targetedAnimation;
  50435. };
  50436. /**
  50437. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50438. * It can add constant keys at begin or end
  50439. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50440. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50441. */
  50442. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50443. if (beginFrame === void 0) { beginFrame = null; }
  50444. if (endFrame === void 0) { endFrame = null; }
  50445. if (beginFrame == null)
  50446. beginFrame = this._from;
  50447. if (endFrame == null)
  50448. endFrame = this._to;
  50449. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50450. var targetedAnimation = this._targetedAnimations[index];
  50451. var keys = targetedAnimation.animation.getKeys();
  50452. var startKey = keys[0];
  50453. var endKey = keys[keys.length - 1];
  50454. if (startKey.frame > beginFrame) {
  50455. var newKey = {
  50456. frame: beginFrame,
  50457. value: startKey.value,
  50458. inTangent: startKey.inTangent,
  50459. outTangent: startKey.outTangent,
  50460. interpolation: startKey.interpolation
  50461. };
  50462. keys.splice(0, 0, newKey);
  50463. }
  50464. if (endKey.frame < endFrame) {
  50465. var newKey = {
  50466. frame: endFrame,
  50467. value: endKey.value,
  50468. inTangent: endKey.outTangent,
  50469. outTangent: endKey.outTangent,
  50470. interpolation: endKey.interpolation
  50471. };
  50472. keys.push(newKey);
  50473. }
  50474. }
  50475. this._from = beginFrame;
  50476. this._to = endFrame;
  50477. return this;
  50478. };
  50479. /**
  50480. * Start all animations on given targets
  50481. * @param loop defines if animations must loop
  50482. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50483. * @param from defines the from key (optional)
  50484. * @param to defines the to key (optional)
  50485. * @returns the current animation group
  50486. */
  50487. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50488. var _this = this;
  50489. if (loop === void 0) { loop = false; }
  50490. if (speedRatio === void 0) { speedRatio = 1; }
  50491. if (this._isStarted || this._targetedAnimations.length === 0) {
  50492. return this;
  50493. }
  50494. var _loop_1 = function (targetedAnimation) {
  50495. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50496. animatable.onAnimationEnd = function () {
  50497. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50498. _this._checkAnimationGroupEnded(animatable);
  50499. };
  50500. this_1._animatables.push(animatable);
  50501. };
  50502. var this_1 = this;
  50503. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50504. var targetedAnimation = _a[_i];
  50505. _loop_1(targetedAnimation);
  50506. }
  50507. this._speedRatio = speedRatio;
  50508. this._isStarted = true;
  50509. return this;
  50510. };
  50511. /**
  50512. * Pause all animations
  50513. */
  50514. AnimationGroup.prototype.pause = function () {
  50515. if (!this._isStarted) {
  50516. return this;
  50517. }
  50518. for (var index = 0; index < this._animatables.length; index++) {
  50519. var animatable = this._animatables[index];
  50520. animatable.pause();
  50521. }
  50522. return this;
  50523. };
  50524. /**
  50525. * Play all animations to initial state
  50526. * This function will start() the animations if they were not started or will restart() them if they were paused
  50527. * @param loop defines if animations must loop
  50528. */
  50529. AnimationGroup.prototype.play = function (loop) {
  50530. // only if all animatables are ready and exist
  50531. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50532. if (loop !== undefined) {
  50533. for (var index = 0; index < this._animatables.length; index++) {
  50534. var animatable = this._animatables[index];
  50535. animatable.loopAnimation = loop;
  50536. }
  50537. }
  50538. this.restart();
  50539. }
  50540. else {
  50541. this.stop();
  50542. this.start(loop, this._speedRatio);
  50543. }
  50544. return this;
  50545. };
  50546. /**
  50547. * Reset all animations to initial state
  50548. */
  50549. AnimationGroup.prototype.reset = function () {
  50550. if (!this._isStarted) {
  50551. return this;
  50552. }
  50553. for (var index = 0; index < this._animatables.length; index++) {
  50554. var animatable = this._animatables[index];
  50555. animatable.reset();
  50556. }
  50557. return this;
  50558. };
  50559. /**
  50560. * Restart animations from key 0
  50561. */
  50562. AnimationGroup.prototype.restart = function () {
  50563. if (!this._isStarted) {
  50564. return this;
  50565. }
  50566. for (var index = 0; index < this._animatables.length; index++) {
  50567. var animatable = this._animatables[index];
  50568. animatable.restart();
  50569. }
  50570. return this;
  50571. };
  50572. /**
  50573. * Stop all animations
  50574. */
  50575. AnimationGroup.prototype.stop = function () {
  50576. if (!this._isStarted) {
  50577. return this;
  50578. }
  50579. for (var index = 0; index < this._animatables.length; index++) {
  50580. var animatable = this._animatables[index];
  50581. animatable.stop();
  50582. }
  50583. this._isStarted = false;
  50584. return this;
  50585. };
  50586. /**
  50587. * Set animation weight for all animatables
  50588. * @param weight defines the weight to use
  50589. * @return the animationGroup
  50590. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50591. */
  50592. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50593. for (var index = 0; index < this._animatables.length; index++) {
  50594. var animatable = this._animatables[index];
  50595. animatable.weight = weight;
  50596. }
  50597. return this;
  50598. };
  50599. /**
  50600. * Synchronize and normalize all animatables with a source animatable
  50601. * @param root defines the root animatable to synchronize with
  50602. * @return the animationGroup
  50603. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50604. */
  50605. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50606. for (var index = 0; index < this._animatables.length; index++) {
  50607. var animatable = this._animatables[index];
  50608. animatable.syncWith(root);
  50609. }
  50610. return this;
  50611. };
  50612. /**
  50613. * Goes to a specific frame in this animation group
  50614. * @param frame the frame number to go to
  50615. * @return the animationGroup
  50616. */
  50617. AnimationGroup.prototype.goToFrame = function (frame) {
  50618. if (!this._isStarted) {
  50619. return this;
  50620. }
  50621. for (var index = 0; index < this._animatables.length; index++) {
  50622. var animatable = this._animatables[index];
  50623. animatable.goToFrame(frame);
  50624. }
  50625. return this;
  50626. };
  50627. /**
  50628. * Dispose all associated resources
  50629. */
  50630. AnimationGroup.prototype.dispose = function () {
  50631. this._targetedAnimations = [];
  50632. this._animatables = [];
  50633. var index = this._scene.animationGroups.indexOf(this);
  50634. if (index > -1) {
  50635. this._scene.animationGroups.splice(index, 1);
  50636. }
  50637. };
  50638. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50639. // animatable should be taken out of the array
  50640. var idx = this._animatables.indexOf(animatable);
  50641. if (idx > -1) {
  50642. this._animatables.splice(idx, 1);
  50643. }
  50644. // all animatables were removed? animation group ended!
  50645. if (this._animatables.length === 0) {
  50646. this._isStarted = false;
  50647. this.onAnimationGroupEndObservable.notifyObservers(this);
  50648. }
  50649. };
  50650. return AnimationGroup;
  50651. }());
  50652. BABYLON.AnimationGroup = AnimationGroup;
  50653. })(BABYLON || (BABYLON = {}));
  50654. //# sourceMappingURL=babylon.animationGroup.js.map
  50655. var BABYLON;
  50656. (function (BABYLON) {
  50657. /**
  50658. * Defines a runtime animation
  50659. */
  50660. var RuntimeAnimation = /** @class */ (function () {
  50661. /**
  50662. * Create a new RuntimeAnimation object
  50663. * @param target defines the target of the animation
  50664. * @param animation defines the source animation object
  50665. * @param scene defines the hosting scene
  50666. * @param host defines the initiating Animatable
  50667. */
  50668. function RuntimeAnimation(target, animation, scene, host) {
  50669. var _this = this;
  50670. this._events = new Array();
  50671. /**
  50672. * The current frame of the runtime animation
  50673. */
  50674. this._currentFrame = 0;
  50675. /**
  50676. * The original value of the runtime animation
  50677. */
  50678. this._originalValue = new Array();
  50679. /**
  50680. * The offsets cache of the runtime animation
  50681. */
  50682. this._offsetsCache = {};
  50683. /**
  50684. * The high limits cache of the runtime animation
  50685. */
  50686. this._highLimitsCache = {};
  50687. /**
  50688. * Specifies if the runtime animation has been stopped
  50689. */
  50690. this._stopped = false;
  50691. /**
  50692. * The blending factor of the runtime animation
  50693. */
  50694. this._blendingFactor = 0;
  50695. /**
  50696. * The target path of the runtime animation
  50697. */
  50698. this._targetPath = "";
  50699. /**
  50700. * The weight of the runtime animation
  50701. */
  50702. this._weight = 1.0;
  50703. /**
  50704. * The ratio offset of the runtime animation
  50705. */
  50706. this._ratioOffset = 0;
  50707. /**
  50708. * The previous delay of the runtime animation
  50709. */
  50710. this._previousDelay = 0;
  50711. /**
  50712. * The previous ratio of the runtime animation
  50713. */
  50714. this._previousRatio = 0;
  50715. this._animation = animation;
  50716. this._target = target;
  50717. this._scene = scene;
  50718. this._host = host;
  50719. animation._runtimeAnimations.push(this);
  50720. // Cloning events locally
  50721. var events = animation.getEvents();
  50722. if (events && events.length > 0) {
  50723. events.forEach(function (e) {
  50724. _this._events.push(e._clone());
  50725. });
  50726. }
  50727. }
  50728. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50729. /**
  50730. * Gets the current frame of the runtime animation
  50731. */
  50732. get: function () {
  50733. return this._currentFrame;
  50734. },
  50735. enumerable: true,
  50736. configurable: true
  50737. });
  50738. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50739. /**
  50740. * Gets the weight of the runtime animation
  50741. */
  50742. get: function () {
  50743. return this._weight;
  50744. },
  50745. enumerable: true,
  50746. configurable: true
  50747. });
  50748. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50749. /**
  50750. * Gets the current value of the runtime animation
  50751. */
  50752. get: function () {
  50753. return this._currentValue;
  50754. },
  50755. enumerable: true,
  50756. configurable: true
  50757. });
  50758. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50759. /**
  50760. * Gets the target path of the runtime animation
  50761. */
  50762. get: function () {
  50763. return this._targetPath;
  50764. },
  50765. enumerable: true,
  50766. configurable: true
  50767. });
  50768. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50769. /**
  50770. * Gets the actual target of the runtime animation
  50771. */
  50772. get: function () {
  50773. return this._activeTarget;
  50774. },
  50775. enumerable: true,
  50776. configurable: true
  50777. });
  50778. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50779. /**
  50780. * Gets the animation from the runtime animation
  50781. */
  50782. get: function () {
  50783. return this._animation;
  50784. },
  50785. enumerable: true,
  50786. configurable: true
  50787. });
  50788. /**
  50789. * Resets the runtime animation to the beginning
  50790. * @param restoreOriginal defines whether to restore the target property to the original value
  50791. */
  50792. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50793. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50794. if (restoreOriginal) {
  50795. if (this._target instanceof Array) {
  50796. var index = 0;
  50797. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50798. var target = _a[_i];
  50799. if (this._originalValue[index] !== undefined) {
  50800. this._setValue(target, this._originalValue[index], -1);
  50801. }
  50802. index++;
  50803. }
  50804. }
  50805. else {
  50806. if (this._originalValue[0] !== undefined) {
  50807. this._setValue(this._target, this._originalValue[0], -1);
  50808. }
  50809. }
  50810. }
  50811. this._offsetsCache = {};
  50812. this._highLimitsCache = {};
  50813. this._currentFrame = 0;
  50814. this._blendingFactor = 0;
  50815. this._originalValue = new Array();
  50816. // Events
  50817. for (var index = 0; index < this._events.length; index++) {
  50818. this._events[index].isDone = false;
  50819. }
  50820. };
  50821. /**
  50822. * Specifies if the runtime animation is stopped
  50823. * @returns Boolean specifying if the runtime animation is stopped
  50824. */
  50825. RuntimeAnimation.prototype.isStopped = function () {
  50826. return this._stopped;
  50827. };
  50828. /**
  50829. * Disposes of the runtime animation
  50830. */
  50831. RuntimeAnimation.prototype.dispose = function () {
  50832. var index = this._animation.runtimeAnimations.indexOf(this);
  50833. if (index > -1) {
  50834. this._animation.runtimeAnimations.splice(index, 1);
  50835. }
  50836. };
  50837. /**
  50838. * Interpolates the animation from the current frame
  50839. * @param currentFrame The frame to interpolate the animation to
  50840. * @param repeatCount The number of times that the animation should loop
  50841. * @param loopMode The type of looping mode to use
  50842. * @param offsetValue Animation offset value
  50843. * @param highLimitValue The high limit value
  50844. * @returns The interpolated value
  50845. */
  50846. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50847. this._currentFrame = currentFrame;
  50848. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50849. this._workValue = BABYLON.Matrix.Zero();
  50850. }
  50851. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50852. };
  50853. /**
  50854. * Apply the interpolated value to the target
  50855. * @param currentValue defines the value computed by the animation
  50856. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50857. */
  50858. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50859. if (weight === void 0) { weight = 1.0; }
  50860. if (this._target instanceof Array) {
  50861. var index = 0;
  50862. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50863. var target = _a[_i];
  50864. this._setValue(target, currentValue, weight, index);
  50865. index++;
  50866. }
  50867. }
  50868. else {
  50869. this._setValue(this._target, currentValue, weight);
  50870. }
  50871. };
  50872. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50873. if (targetIndex === void 0) { targetIndex = 0; }
  50874. // Set value
  50875. var path;
  50876. var destination;
  50877. var targetPropertyPath = this._animation.targetPropertyPath;
  50878. if (targetPropertyPath.length > 1) {
  50879. var property = target[targetPropertyPath[0]];
  50880. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50881. property = property[targetPropertyPath[index]];
  50882. }
  50883. path = targetPropertyPath[targetPropertyPath.length - 1];
  50884. destination = property;
  50885. }
  50886. else {
  50887. path = targetPropertyPath[0];
  50888. destination = target;
  50889. }
  50890. this._targetPath = path;
  50891. this._activeTarget = destination;
  50892. this._weight = weight;
  50893. if (this._originalValue[targetIndex] === undefined) {
  50894. var originalValue = void 0;
  50895. if (destination.getRestPose && path === "_matrix") { // For bones
  50896. originalValue = destination.getRestPose();
  50897. }
  50898. else {
  50899. originalValue = destination[path];
  50900. }
  50901. if (originalValue && originalValue.clone) {
  50902. this._originalValue[targetIndex] = originalValue.clone();
  50903. }
  50904. else {
  50905. this._originalValue[targetIndex] = originalValue;
  50906. }
  50907. }
  50908. // Blending
  50909. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50910. if (enableBlending && this._blendingFactor <= 1.0) {
  50911. if (!this._originalBlendValue) {
  50912. var originalValue = destination[path];
  50913. if (originalValue.clone) {
  50914. this._originalBlendValue = originalValue.clone();
  50915. }
  50916. else {
  50917. this._originalBlendValue = originalValue;
  50918. }
  50919. }
  50920. if (this._originalBlendValue.m) { // Matrix
  50921. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50922. if (this._currentValue) {
  50923. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50924. }
  50925. else {
  50926. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50927. }
  50928. }
  50929. else {
  50930. if (this._currentValue) {
  50931. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50932. }
  50933. else {
  50934. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50935. }
  50936. }
  50937. }
  50938. else {
  50939. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50940. }
  50941. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50942. this._blendingFactor += blendingSpeed;
  50943. }
  50944. else {
  50945. this._currentValue = currentValue;
  50946. }
  50947. if (weight !== -1.0) {
  50948. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50949. }
  50950. else {
  50951. destination[path] = this._currentValue;
  50952. }
  50953. if (target.markAsDirty) {
  50954. target.markAsDirty(this._animation.targetProperty);
  50955. }
  50956. };
  50957. /**
  50958. * Gets the loop pmode of the runtime animation
  50959. * @returns Loop Mode
  50960. */
  50961. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50962. if (this._target && this._target.animationPropertiesOverride) {
  50963. return this._target.animationPropertiesOverride.loopMode;
  50964. }
  50965. return this._animation.loopMode;
  50966. };
  50967. /**
  50968. * Move the current animation to a given frame
  50969. * @param frame defines the frame to move to
  50970. */
  50971. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50972. var keys = this._animation.getKeys();
  50973. if (frame < keys[0].frame) {
  50974. frame = keys[0].frame;
  50975. }
  50976. else if (frame > keys[keys.length - 1].frame) {
  50977. frame = keys[keys.length - 1].frame;
  50978. }
  50979. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50980. this.setValue(currentValue, -1);
  50981. };
  50982. /**
  50983. * @hidden Internal use only
  50984. */
  50985. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50986. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50987. this._ratioOffset = this._previousRatio - newRatio;
  50988. };
  50989. /**
  50990. * Execute the current animation
  50991. * @param delay defines the delay to add to the current frame
  50992. * @param from defines the lower bound of the animation range
  50993. * @param to defines the upper bound of the animation range
  50994. * @param loop defines if the current animation must loop
  50995. * @param speedRatio defines the current speed ratio
  50996. * @param weight defines the weight of the animation (default is -1 so no weight)
  50997. * @returns a boolean indicating if the animation has ended
  50998. */
  50999. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51000. if (weight === void 0) { weight = -1.0; }
  51001. var targetPropertyPath = this._animation.targetPropertyPath;
  51002. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51003. this._stopped = true;
  51004. return false;
  51005. }
  51006. var returnValue = true;
  51007. var keys = this._animation.getKeys();
  51008. // Adding a start key at frame 0 if missing
  51009. if (keys[0].frame !== 0) {
  51010. var newKey = { frame: 0, value: keys[0].value };
  51011. keys.splice(0, 0, newKey);
  51012. }
  51013. // Check limits
  51014. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51015. from = keys[0].frame;
  51016. }
  51017. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51018. to = keys[keys.length - 1].frame;
  51019. }
  51020. //to and from cannot be the same key
  51021. if (from === to) {
  51022. if (from > keys[0].frame) {
  51023. from--;
  51024. }
  51025. else if (to < keys[keys.length - 1].frame) {
  51026. to++;
  51027. }
  51028. }
  51029. // Compute ratio
  51030. var range = to - from;
  51031. var offsetValue;
  51032. // ratio represents the frame delta between from and to
  51033. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51034. var highLimitValue = 0;
  51035. this._previousDelay = delay;
  51036. this._previousRatio = ratio;
  51037. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51038. returnValue = false;
  51039. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51040. }
  51041. else {
  51042. // Get max value if required
  51043. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51044. var keyOffset = to.toString() + from.toString();
  51045. if (!this._offsetsCache[keyOffset]) {
  51046. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51047. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51048. switch (this._animation.dataType) {
  51049. // Float
  51050. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51051. this._offsetsCache[keyOffset] = toValue - fromValue;
  51052. break;
  51053. // Quaternion
  51054. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51055. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51056. break;
  51057. // Vector3
  51058. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51059. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51060. // Vector2
  51061. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51062. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51063. // Size
  51064. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51065. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51066. // Color3
  51067. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51068. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51069. default:
  51070. break;
  51071. }
  51072. this._highLimitsCache[keyOffset] = toValue;
  51073. }
  51074. highLimitValue = this._highLimitsCache[keyOffset];
  51075. offsetValue = this._offsetsCache[keyOffset];
  51076. }
  51077. }
  51078. if (offsetValue === undefined) {
  51079. switch (this._animation.dataType) {
  51080. // Float
  51081. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51082. offsetValue = 0;
  51083. break;
  51084. // Quaternion
  51085. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51086. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51087. break;
  51088. // Vector3
  51089. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51090. offsetValue = BABYLON.Vector3.Zero();
  51091. break;
  51092. // Vector2
  51093. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51094. offsetValue = BABYLON.Vector2.Zero();
  51095. break;
  51096. // Size
  51097. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51098. offsetValue = BABYLON.Size.Zero();
  51099. break;
  51100. // Color3
  51101. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51102. offsetValue = BABYLON.Color3.Black();
  51103. }
  51104. }
  51105. // Compute value
  51106. var repeatCount = (ratio / range) >> 0;
  51107. var currentFrame = returnValue ? from + ratio % range : to;
  51108. // Need to normalize?
  51109. if (this._host && this._host.syncRoot) {
  51110. var syncRoot = this._host.syncRoot;
  51111. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51112. currentFrame = from + (to - from) * hostNormalizedFrame;
  51113. }
  51114. // Reset events if looping
  51115. var events = this._events;
  51116. if (range > 0 && this.currentFrame > currentFrame ||
  51117. range < 0 && this.currentFrame < currentFrame) {
  51118. // Need to reset animation events
  51119. for (var index = 0; index < events.length; index++) {
  51120. if (!events[index].onlyOnce) {
  51121. // reset event, the animation is looping
  51122. events[index].isDone = false;
  51123. }
  51124. }
  51125. }
  51126. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51127. // Set value
  51128. this.setValue(currentValue, weight);
  51129. // Check events
  51130. for (var index = 0; index < events.length; index++) {
  51131. // Make sure current frame has passed event frame and that event frame is within the current range
  51132. // Also, handle both forward and reverse animations
  51133. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51134. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51135. var event = events[index];
  51136. if (!event.isDone) {
  51137. // If event should be done only once, remove it.
  51138. if (event.onlyOnce) {
  51139. events.splice(index, 1);
  51140. index--;
  51141. }
  51142. event.isDone = true;
  51143. event.action();
  51144. } // Don't do anything if the event has already be done.
  51145. }
  51146. }
  51147. if (!returnValue) {
  51148. this._stopped = true;
  51149. }
  51150. return returnValue;
  51151. };
  51152. return RuntimeAnimation;
  51153. }());
  51154. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51155. })(BABYLON || (BABYLON = {}));
  51156. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51157. var BABYLON;
  51158. (function (BABYLON) {
  51159. var Animatable = /** @class */ (function () {
  51160. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51161. if (fromFrame === void 0) { fromFrame = 0; }
  51162. if (toFrame === void 0) { toFrame = 100; }
  51163. if (loopAnimation === void 0) { loopAnimation = false; }
  51164. if (speedRatio === void 0) { speedRatio = 1.0; }
  51165. this.target = target;
  51166. this.fromFrame = fromFrame;
  51167. this.toFrame = toFrame;
  51168. this.loopAnimation = loopAnimation;
  51169. this.onAnimationEnd = onAnimationEnd;
  51170. this._localDelayOffset = null;
  51171. this._pausedDelay = null;
  51172. this._runtimeAnimations = new Array();
  51173. this._paused = false;
  51174. this._speedRatio = 1;
  51175. this._weight = -1.0;
  51176. this.animationStarted = false;
  51177. /**
  51178. * Observer raised when the animation ends
  51179. */
  51180. this.onAnimationEndObservable = new BABYLON.Observable();
  51181. this._scene = scene;
  51182. if (animations) {
  51183. this.appendAnimations(target, animations);
  51184. }
  51185. this._speedRatio = speedRatio;
  51186. scene._activeAnimatables.push(this);
  51187. }
  51188. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51189. /**
  51190. * Gets the root Animatable used to synchronize and normalize animations
  51191. */
  51192. get: function () {
  51193. return this._syncRoot;
  51194. },
  51195. enumerable: true,
  51196. configurable: true
  51197. });
  51198. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51199. /**
  51200. * Gets the current frame of the first RuntimeAnimation
  51201. * Used to synchronize Animatables
  51202. */
  51203. get: function () {
  51204. if (this._runtimeAnimations.length === 0) {
  51205. return 0;
  51206. }
  51207. return this._runtimeAnimations[0].currentFrame;
  51208. },
  51209. enumerable: true,
  51210. configurable: true
  51211. });
  51212. Object.defineProperty(Animatable.prototype, "weight", {
  51213. /**
  51214. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51215. */
  51216. get: function () {
  51217. return this._weight;
  51218. },
  51219. set: function (value) {
  51220. if (value === -1) { // -1 is ok and means no weight
  51221. this._weight = -1;
  51222. return;
  51223. }
  51224. // Else weight must be in [0, 1] range
  51225. this._weight = Math.min(Math.max(value, 0), 1.0);
  51226. },
  51227. enumerable: true,
  51228. configurable: true
  51229. });
  51230. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51231. /**
  51232. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51233. */
  51234. get: function () {
  51235. return this._speedRatio;
  51236. },
  51237. set: function (value) {
  51238. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51239. var animation = this._runtimeAnimations[index];
  51240. animation._prepareForSpeedRatioChange(value);
  51241. }
  51242. this._speedRatio = value;
  51243. },
  51244. enumerable: true,
  51245. configurable: true
  51246. });
  51247. // Methods
  51248. /**
  51249. * Synchronize and normalize current Animatable with a source Animatable
  51250. * This is useful when using animation weights and when animations are not of the same length
  51251. * @param root defines the root Animatable to synchronize with
  51252. * @returns the current Animatable
  51253. */
  51254. Animatable.prototype.syncWith = function (root) {
  51255. this._syncRoot = root;
  51256. if (root) {
  51257. // Make sure this animatable will animate after the root
  51258. var index = this._scene._activeAnimatables.indexOf(this);
  51259. if (index > -1) {
  51260. this._scene._activeAnimatables.splice(index, 1);
  51261. this._scene._activeAnimatables.push(this);
  51262. }
  51263. }
  51264. return this;
  51265. };
  51266. Animatable.prototype.getAnimations = function () {
  51267. return this._runtimeAnimations;
  51268. };
  51269. Animatable.prototype.appendAnimations = function (target, animations) {
  51270. for (var index = 0; index < animations.length; index++) {
  51271. var animation = animations[index];
  51272. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51273. }
  51274. };
  51275. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51276. var runtimeAnimations = this._runtimeAnimations;
  51277. for (var index = 0; index < runtimeAnimations.length; index++) {
  51278. if (runtimeAnimations[index].animation.targetProperty === property) {
  51279. return runtimeAnimations[index].animation;
  51280. }
  51281. }
  51282. return null;
  51283. };
  51284. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51285. var runtimeAnimations = this._runtimeAnimations;
  51286. for (var index = 0; index < runtimeAnimations.length; index++) {
  51287. if (runtimeAnimations[index].animation.targetProperty === property) {
  51288. return runtimeAnimations[index];
  51289. }
  51290. }
  51291. return null;
  51292. };
  51293. Animatable.prototype.reset = function () {
  51294. var runtimeAnimations = this._runtimeAnimations;
  51295. for (var index = 0; index < runtimeAnimations.length; index++) {
  51296. runtimeAnimations[index].reset(true);
  51297. }
  51298. this._localDelayOffset = null;
  51299. this._pausedDelay = null;
  51300. };
  51301. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51302. var runtimeAnimations = this._runtimeAnimations;
  51303. for (var index = 0; index < runtimeAnimations.length; index++) {
  51304. runtimeAnimations[index].animation.enableBlending = true;
  51305. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51306. }
  51307. };
  51308. Animatable.prototype.disableBlending = function () {
  51309. var runtimeAnimations = this._runtimeAnimations;
  51310. for (var index = 0; index < runtimeAnimations.length; index++) {
  51311. runtimeAnimations[index].animation.enableBlending = false;
  51312. }
  51313. };
  51314. Animatable.prototype.goToFrame = function (frame) {
  51315. var runtimeAnimations = this._runtimeAnimations;
  51316. if (runtimeAnimations[0]) {
  51317. var fps = runtimeAnimations[0].animation.framePerSecond;
  51318. var currentFrame = runtimeAnimations[0].currentFrame;
  51319. var adjustTime = frame - currentFrame;
  51320. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51321. if (this._localDelayOffset === null) {
  51322. this._localDelayOffset = 0;
  51323. }
  51324. this._localDelayOffset -= delay;
  51325. }
  51326. for (var index = 0; index < runtimeAnimations.length; index++) {
  51327. runtimeAnimations[index].goToFrame(frame);
  51328. }
  51329. };
  51330. Animatable.prototype.pause = function () {
  51331. if (this._paused) {
  51332. return;
  51333. }
  51334. this._paused = true;
  51335. };
  51336. Animatable.prototype.restart = function () {
  51337. this._paused = false;
  51338. };
  51339. Animatable.prototype._raiseOnAnimationEnd = function () {
  51340. if (this.onAnimationEnd) {
  51341. this.onAnimationEnd();
  51342. }
  51343. this.onAnimationEndObservable.notifyObservers(this);
  51344. };
  51345. Animatable.prototype.stop = function (animationName) {
  51346. if (animationName) {
  51347. var idx = this._scene._activeAnimatables.indexOf(this);
  51348. if (idx > -1) {
  51349. var runtimeAnimations = this._runtimeAnimations;
  51350. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51351. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51352. continue;
  51353. }
  51354. runtimeAnimations[index].dispose();
  51355. runtimeAnimations.splice(index, 1);
  51356. }
  51357. if (runtimeAnimations.length == 0) {
  51358. this._scene._activeAnimatables.splice(idx, 1);
  51359. this._raiseOnAnimationEnd();
  51360. }
  51361. }
  51362. }
  51363. else {
  51364. var index = this._scene._activeAnimatables.indexOf(this);
  51365. if (index > -1) {
  51366. this._scene._activeAnimatables.splice(index, 1);
  51367. var runtimeAnimations = this._runtimeAnimations;
  51368. for (var index = 0; index < runtimeAnimations.length; index++) {
  51369. runtimeAnimations[index].dispose();
  51370. }
  51371. this._raiseOnAnimationEnd();
  51372. }
  51373. }
  51374. };
  51375. /**
  51376. * Wait asynchronously for the animation to end
  51377. * @returns a promise which will be fullfilled when the animation ends
  51378. */
  51379. Animatable.prototype.waitAsync = function () {
  51380. var _this = this;
  51381. return new Promise(function (resolve, reject) {
  51382. _this.onAnimationEndObservable.add(function () {
  51383. resolve(_this);
  51384. }, undefined, undefined, _this, true);
  51385. });
  51386. };
  51387. /** @hidden */
  51388. Animatable.prototype._animate = function (delay) {
  51389. if (this._paused) {
  51390. this.animationStarted = false;
  51391. if (this._pausedDelay === null) {
  51392. this._pausedDelay = delay;
  51393. }
  51394. return true;
  51395. }
  51396. if (this._localDelayOffset === null) {
  51397. this._localDelayOffset = delay;
  51398. this._pausedDelay = null;
  51399. }
  51400. else if (this._pausedDelay !== null) {
  51401. this._localDelayOffset += delay - this._pausedDelay;
  51402. this._pausedDelay = null;
  51403. }
  51404. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51405. return true;
  51406. }
  51407. // Animating
  51408. var running = false;
  51409. var runtimeAnimations = this._runtimeAnimations;
  51410. var index;
  51411. for (index = 0; index < runtimeAnimations.length; index++) {
  51412. var animation = runtimeAnimations[index];
  51413. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51414. running = running || isRunning;
  51415. }
  51416. this.animationStarted = running;
  51417. if (!running) {
  51418. // Remove from active animatables
  51419. index = this._scene._activeAnimatables.indexOf(this);
  51420. this._scene._activeAnimatables.splice(index, 1);
  51421. // Dispose all runtime animations
  51422. for (index = 0; index < runtimeAnimations.length; index++) {
  51423. runtimeAnimations[index].dispose();
  51424. }
  51425. this._raiseOnAnimationEnd();
  51426. this.onAnimationEnd = null;
  51427. this.onAnimationEndObservable.clear();
  51428. }
  51429. return running;
  51430. };
  51431. return Animatable;
  51432. }());
  51433. BABYLON.Animatable = Animatable;
  51434. })(BABYLON || (BABYLON = {}));
  51435. //# sourceMappingURL=babylon.animatable.js.map
  51436. var BABYLON;
  51437. (function (BABYLON) {
  51438. var EasingFunction = /** @class */ (function () {
  51439. function EasingFunction() {
  51440. // Properties
  51441. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51442. }
  51443. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51444. get: function () {
  51445. return EasingFunction._EASINGMODE_EASEIN;
  51446. },
  51447. enumerable: true,
  51448. configurable: true
  51449. });
  51450. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51451. get: function () {
  51452. return EasingFunction._EASINGMODE_EASEOUT;
  51453. },
  51454. enumerable: true,
  51455. configurable: true
  51456. });
  51457. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51458. get: function () {
  51459. return EasingFunction._EASINGMODE_EASEINOUT;
  51460. },
  51461. enumerable: true,
  51462. configurable: true
  51463. });
  51464. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51465. var n = Math.min(Math.max(easingMode, 0), 2);
  51466. this._easingMode = n;
  51467. };
  51468. EasingFunction.prototype.getEasingMode = function () {
  51469. return this._easingMode;
  51470. };
  51471. EasingFunction.prototype.easeInCore = function (gradient) {
  51472. throw new Error('You must implement this method');
  51473. };
  51474. EasingFunction.prototype.ease = function (gradient) {
  51475. switch (this._easingMode) {
  51476. case EasingFunction.EASINGMODE_EASEIN:
  51477. return this.easeInCore(gradient);
  51478. case EasingFunction.EASINGMODE_EASEOUT:
  51479. return (1 - this.easeInCore(1 - gradient));
  51480. }
  51481. if (gradient >= 0.5) {
  51482. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51483. }
  51484. return (this.easeInCore(gradient * 2) * 0.5);
  51485. };
  51486. //Statics
  51487. EasingFunction._EASINGMODE_EASEIN = 0;
  51488. EasingFunction._EASINGMODE_EASEOUT = 1;
  51489. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51490. return EasingFunction;
  51491. }());
  51492. BABYLON.EasingFunction = EasingFunction;
  51493. var CircleEase = /** @class */ (function (_super) {
  51494. __extends(CircleEase, _super);
  51495. function CircleEase() {
  51496. return _super !== null && _super.apply(this, arguments) || this;
  51497. }
  51498. CircleEase.prototype.easeInCore = function (gradient) {
  51499. gradient = Math.max(0, Math.min(1, gradient));
  51500. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51501. };
  51502. return CircleEase;
  51503. }(EasingFunction));
  51504. BABYLON.CircleEase = CircleEase;
  51505. var BackEase = /** @class */ (function (_super) {
  51506. __extends(BackEase, _super);
  51507. function BackEase(amplitude) {
  51508. if (amplitude === void 0) { amplitude = 1; }
  51509. var _this = _super.call(this) || this;
  51510. _this.amplitude = amplitude;
  51511. return _this;
  51512. }
  51513. BackEase.prototype.easeInCore = function (gradient) {
  51514. var num = Math.max(0, this.amplitude);
  51515. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51516. };
  51517. return BackEase;
  51518. }(EasingFunction));
  51519. BABYLON.BackEase = BackEase;
  51520. var BounceEase = /** @class */ (function (_super) {
  51521. __extends(BounceEase, _super);
  51522. function BounceEase(bounces, bounciness) {
  51523. if (bounces === void 0) { bounces = 3; }
  51524. if (bounciness === void 0) { bounciness = 2; }
  51525. var _this = _super.call(this) || this;
  51526. _this.bounces = bounces;
  51527. _this.bounciness = bounciness;
  51528. return _this;
  51529. }
  51530. BounceEase.prototype.easeInCore = function (gradient) {
  51531. var y = Math.max(0.0, this.bounces);
  51532. var bounciness = this.bounciness;
  51533. if (bounciness <= 1.0) {
  51534. bounciness = 1.001;
  51535. }
  51536. var num9 = Math.pow(bounciness, y);
  51537. var num5 = 1.0 - bounciness;
  51538. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51539. var num15 = gradient * num4;
  51540. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51541. var num3 = Math.floor(num65);
  51542. var num13 = num3 + 1.0;
  51543. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51544. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51545. var num7 = (num8 + num12) * 0.5;
  51546. var num6 = gradient - num7;
  51547. var num2 = num7 - num8;
  51548. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51549. };
  51550. return BounceEase;
  51551. }(EasingFunction));
  51552. BABYLON.BounceEase = BounceEase;
  51553. var CubicEase = /** @class */ (function (_super) {
  51554. __extends(CubicEase, _super);
  51555. function CubicEase() {
  51556. return _super !== null && _super.apply(this, arguments) || this;
  51557. }
  51558. CubicEase.prototype.easeInCore = function (gradient) {
  51559. return (gradient * gradient * gradient);
  51560. };
  51561. return CubicEase;
  51562. }(EasingFunction));
  51563. BABYLON.CubicEase = CubicEase;
  51564. var ElasticEase = /** @class */ (function (_super) {
  51565. __extends(ElasticEase, _super);
  51566. function ElasticEase(oscillations, springiness) {
  51567. if (oscillations === void 0) { oscillations = 3; }
  51568. if (springiness === void 0) { springiness = 3; }
  51569. var _this = _super.call(this) || this;
  51570. _this.oscillations = oscillations;
  51571. _this.springiness = springiness;
  51572. return _this;
  51573. }
  51574. ElasticEase.prototype.easeInCore = function (gradient) {
  51575. var num2;
  51576. var num3 = Math.max(0.0, this.oscillations);
  51577. var num = Math.max(0.0, this.springiness);
  51578. if (num == 0) {
  51579. num2 = gradient;
  51580. }
  51581. else {
  51582. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51583. }
  51584. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51585. };
  51586. return ElasticEase;
  51587. }(EasingFunction));
  51588. BABYLON.ElasticEase = ElasticEase;
  51589. var ExponentialEase = /** @class */ (function (_super) {
  51590. __extends(ExponentialEase, _super);
  51591. function ExponentialEase(exponent) {
  51592. if (exponent === void 0) { exponent = 2; }
  51593. var _this = _super.call(this) || this;
  51594. _this.exponent = exponent;
  51595. return _this;
  51596. }
  51597. ExponentialEase.prototype.easeInCore = function (gradient) {
  51598. if (this.exponent <= 0) {
  51599. return gradient;
  51600. }
  51601. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51602. };
  51603. return ExponentialEase;
  51604. }(EasingFunction));
  51605. BABYLON.ExponentialEase = ExponentialEase;
  51606. var PowerEase = /** @class */ (function (_super) {
  51607. __extends(PowerEase, _super);
  51608. function PowerEase(power) {
  51609. if (power === void 0) { power = 2; }
  51610. var _this = _super.call(this) || this;
  51611. _this.power = power;
  51612. return _this;
  51613. }
  51614. PowerEase.prototype.easeInCore = function (gradient) {
  51615. var y = Math.max(0.0, this.power);
  51616. return Math.pow(gradient, y);
  51617. };
  51618. return PowerEase;
  51619. }(EasingFunction));
  51620. BABYLON.PowerEase = PowerEase;
  51621. var QuadraticEase = /** @class */ (function (_super) {
  51622. __extends(QuadraticEase, _super);
  51623. function QuadraticEase() {
  51624. return _super !== null && _super.apply(this, arguments) || this;
  51625. }
  51626. QuadraticEase.prototype.easeInCore = function (gradient) {
  51627. return (gradient * gradient);
  51628. };
  51629. return QuadraticEase;
  51630. }(EasingFunction));
  51631. BABYLON.QuadraticEase = QuadraticEase;
  51632. var QuarticEase = /** @class */ (function (_super) {
  51633. __extends(QuarticEase, _super);
  51634. function QuarticEase() {
  51635. return _super !== null && _super.apply(this, arguments) || this;
  51636. }
  51637. QuarticEase.prototype.easeInCore = function (gradient) {
  51638. return (gradient * gradient * gradient * gradient);
  51639. };
  51640. return QuarticEase;
  51641. }(EasingFunction));
  51642. BABYLON.QuarticEase = QuarticEase;
  51643. var QuinticEase = /** @class */ (function (_super) {
  51644. __extends(QuinticEase, _super);
  51645. function QuinticEase() {
  51646. return _super !== null && _super.apply(this, arguments) || this;
  51647. }
  51648. QuinticEase.prototype.easeInCore = function (gradient) {
  51649. return (gradient * gradient * gradient * gradient * gradient);
  51650. };
  51651. return QuinticEase;
  51652. }(EasingFunction));
  51653. BABYLON.QuinticEase = QuinticEase;
  51654. var SineEase = /** @class */ (function (_super) {
  51655. __extends(SineEase, _super);
  51656. function SineEase() {
  51657. return _super !== null && _super.apply(this, arguments) || this;
  51658. }
  51659. SineEase.prototype.easeInCore = function (gradient) {
  51660. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51661. };
  51662. return SineEase;
  51663. }(EasingFunction));
  51664. BABYLON.SineEase = SineEase;
  51665. var BezierCurveEase = /** @class */ (function (_super) {
  51666. __extends(BezierCurveEase, _super);
  51667. function BezierCurveEase(x1, y1, x2, y2) {
  51668. if (x1 === void 0) { x1 = 0; }
  51669. if (y1 === void 0) { y1 = 0; }
  51670. if (x2 === void 0) { x2 = 1; }
  51671. if (y2 === void 0) { y2 = 1; }
  51672. var _this = _super.call(this) || this;
  51673. _this.x1 = x1;
  51674. _this.y1 = y1;
  51675. _this.x2 = x2;
  51676. _this.y2 = y2;
  51677. return _this;
  51678. }
  51679. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51680. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51681. };
  51682. return BezierCurveEase;
  51683. }(EasingFunction));
  51684. BABYLON.BezierCurveEase = BezierCurveEase;
  51685. })(BABYLON || (BABYLON = {}));
  51686. //# sourceMappingURL=babylon.easing.js.map
  51687. var BABYLON;
  51688. (function (BABYLON) {
  51689. /**
  51690. * A Condition applied to an Action
  51691. */
  51692. var Condition = /** @class */ (function () {
  51693. /**
  51694. * Creates a new Condition
  51695. * @param actionManager the manager of the action the condition is applied to
  51696. */
  51697. function Condition(actionManager) {
  51698. this._actionManager = actionManager;
  51699. }
  51700. /**
  51701. * Check if the current condition is valid
  51702. * @returns a boolean
  51703. */
  51704. Condition.prototype.isValid = function () {
  51705. return true;
  51706. };
  51707. /**
  51708. * Internal only
  51709. * @hidden
  51710. */
  51711. Condition.prototype._getProperty = function (propertyPath) {
  51712. return this._actionManager._getProperty(propertyPath);
  51713. };
  51714. /**
  51715. * Internal only
  51716. * @hidden
  51717. */
  51718. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51719. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51720. };
  51721. /**
  51722. * Serialize placeholder for child classes
  51723. * @returns the serialized object
  51724. */
  51725. Condition.prototype.serialize = function () {
  51726. };
  51727. /**
  51728. * Internal only
  51729. * @hidden
  51730. */
  51731. Condition.prototype._serialize = function (serializedCondition) {
  51732. return {
  51733. type: 2,
  51734. children: [],
  51735. name: serializedCondition.name,
  51736. properties: serializedCondition.properties
  51737. };
  51738. };
  51739. return Condition;
  51740. }());
  51741. BABYLON.Condition = Condition;
  51742. /**
  51743. * Defines specific conditional operators as extensions of Condition
  51744. */
  51745. var ValueCondition = /** @class */ (function (_super) {
  51746. __extends(ValueCondition, _super);
  51747. /**
  51748. * Creates a new ValueCondition
  51749. * @param actionManager manager for the action the condition applies to
  51750. * @param target for the action
  51751. * @param propertyPath path to specify the property of the target the conditional operator uses
  51752. * @param value the value compared by the conditional operator against the current value of the property
  51753. * @param operator the conditional operator, default ValueCondition.IsEqual
  51754. */
  51755. function ValueCondition(actionManager, target,
  51756. /** path to specify the property of the target the conditional operator uses */
  51757. propertyPath,
  51758. /** the value compared by the conditional operator against the current value of the property */
  51759. value,
  51760. /** the conditional operator, default ValueCondition.IsEqual */
  51761. operator) {
  51762. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51763. var _this = _super.call(this, actionManager) || this;
  51764. _this.propertyPath = propertyPath;
  51765. _this.value = value;
  51766. _this.operator = operator;
  51767. _this._target = target;
  51768. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51769. _this._property = _this._getProperty(_this.propertyPath);
  51770. return _this;
  51771. }
  51772. Object.defineProperty(ValueCondition, "IsEqual", {
  51773. /**
  51774. * returns the number for IsEqual
  51775. */
  51776. get: function () {
  51777. return ValueCondition._IsEqual;
  51778. },
  51779. enumerable: true,
  51780. configurable: true
  51781. });
  51782. Object.defineProperty(ValueCondition, "IsDifferent", {
  51783. /**
  51784. * Returns the number for IsDifferent
  51785. */
  51786. get: function () {
  51787. return ValueCondition._IsDifferent;
  51788. },
  51789. enumerable: true,
  51790. configurable: true
  51791. });
  51792. Object.defineProperty(ValueCondition, "IsGreater", {
  51793. /**
  51794. * Returns the number for IsGreater
  51795. */
  51796. get: function () {
  51797. return ValueCondition._IsGreater;
  51798. },
  51799. enumerable: true,
  51800. configurable: true
  51801. });
  51802. Object.defineProperty(ValueCondition, "IsLesser", {
  51803. /**
  51804. * Returns the number for IsLesser
  51805. */
  51806. get: function () {
  51807. return ValueCondition._IsLesser;
  51808. },
  51809. enumerable: true,
  51810. configurable: true
  51811. });
  51812. /**
  51813. * Compares the given value with the property value for the specified conditional operator
  51814. * @returns the result of the comparison
  51815. */
  51816. ValueCondition.prototype.isValid = function () {
  51817. switch (this.operator) {
  51818. case ValueCondition.IsGreater:
  51819. return this._effectiveTarget[this._property] > this.value;
  51820. case ValueCondition.IsLesser:
  51821. return this._effectiveTarget[this._property] < this.value;
  51822. case ValueCondition.IsEqual:
  51823. case ValueCondition.IsDifferent:
  51824. var check;
  51825. if (this.value.equals) {
  51826. check = this.value.equals(this._effectiveTarget[this._property]);
  51827. }
  51828. else {
  51829. check = this.value === this._effectiveTarget[this._property];
  51830. }
  51831. return this.operator === ValueCondition.IsEqual ? check : !check;
  51832. }
  51833. return false;
  51834. };
  51835. /**
  51836. * Serialize the ValueCondition into a JSON compatible object
  51837. * @returns serialization object
  51838. */
  51839. ValueCondition.prototype.serialize = function () {
  51840. return this._serialize({
  51841. name: "ValueCondition",
  51842. properties: [
  51843. BABYLON.Action._GetTargetProperty(this._target),
  51844. { name: "propertyPath", value: this.propertyPath },
  51845. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51846. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51847. ]
  51848. });
  51849. };
  51850. /**
  51851. * Gets the name of the conditional operator for the ValueCondition
  51852. * @param operator the conditional operator
  51853. * @returns the name
  51854. */
  51855. ValueCondition.GetOperatorName = function (operator) {
  51856. switch (operator) {
  51857. case ValueCondition._IsEqual: return "IsEqual";
  51858. case ValueCondition._IsDifferent: return "IsDifferent";
  51859. case ValueCondition._IsGreater: return "IsGreater";
  51860. case ValueCondition._IsLesser: return "IsLesser";
  51861. default: return "";
  51862. }
  51863. };
  51864. /**
  51865. * Internal only
  51866. * @hidden
  51867. */
  51868. ValueCondition._IsEqual = 0;
  51869. /**
  51870. * Internal only
  51871. * @hidden
  51872. */
  51873. ValueCondition._IsDifferent = 1;
  51874. /**
  51875. * Internal only
  51876. * @hidden
  51877. */
  51878. ValueCondition._IsGreater = 2;
  51879. /**
  51880. * Internal only
  51881. * @hidden
  51882. */
  51883. ValueCondition._IsLesser = 3;
  51884. return ValueCondition;
  51885. }(Condition));
  51886. BABYLON.ValueCondition = ValueCondition;
  51887. /**
  51888. * Defines a predicate condition as an extension of Condition
  51889. */
  51890. var PredicateCondition = /** @class */ (function (_super) {
  51891. __extends(PredicateCondition, _super);
  51892. /**
  51893. * Creates a new PredicateCondition
  51894. * @param actionManager manager for the action the condition applies to
  51895. * @param predicate defines the predicate function used to validate the condition
  51896. */
  51897. function PredicateCondition(actionManager,
  51898. /** defines the predicate function used to validate the condition */
  51899. predicate) {
  51900. var _this = _super.call(this, actionManager) || this;
  51901. _this.predicate = predicate;
  51902. return _this;
  51903. }
  51904. /**
  51905. * @returns the validity of the predicate condition
  51906. */
  51907. PredicateCondition.prototype.isValid = function () {
  51908. return this.predicate();
  51909. };
  51910. return PredicateCondition;
  51911. }(Condition));
  51912. BABYLON.PredicateCondition = PredicateCondition;
  51913. /**
  51914. * Defines a state condition as an extension of Condition
  51915. */
  51916. var StateCondition = /** @class */ (function (_super) {
  51917. __extends(StateCondition, _super);
  51918. /**
  51919. * Creates a new StateCondition
  51920. * @param actionManager manager for the action the condition applies to
  51921. * @param target of the condition
  51922. * @param value to compare with target state
  51923. */
  51924. function StateCondition(actionManager, target, value) {
  51925. var _this = _super.call(this, actionManager) || this;
  51926. _this.value = value;
  51927. _this._target = target;
  51928. return _this;
  51929. }
  51930. /**
  51931. * @returns the validity of the state
  51932. */
  51933. StateCondition.prototype.isValid = function () {
  51934. return this._target.state === this.value;
  51935. };
  51936. /**
  51937. * Serialize the StateCondition into a JSON compatible object
  51938. * @returns serialization object
  51939. */
  51940. StateCondition.prototype.serialize = function () {
  51941. return this._serialize({
  51942. name: "StateCondition",
  51943. properties: [
  51944. BABYLON.Action._GetTargetProperty(this._target),
  51945. { name: "value", value: this.value }
  51946. ]
  51947. });
  51948. };
  51949. return StateCondition;
  51950. }(Condition));
  51951. BABYLON.StateCondition = StateCondition;
  51952. })(BABYLON || (BABYLON = {}));
  51953. //# sourceMappingURL=babylon.condition.js.map
  51954. var BABYLON;
  51955. (function (BABYLON) {
  51956. /**
  51957. * The action to be carried out following a trigger
  51958. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51959. */
  51960. var Action = /** @class */ (function () {
  51961. /**
  51962. * Creates a new Action
  51963. * @param triggerOptions the trigger, with or without parameters, for the action
  51964. * @param condition an optional determinant of action
  51965. */
  51966. function Action(
  51967. /** the trigger, with or without parameters, for the action */
  51968. triggerOptions, condition) {
  51969. this.triggerOptions = triggerOptions;
  51970. /**
  51971. * An event triggered prior to action being executed.
  51972. */
  51973. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51974. if (triggerOptions.parameter) {
  51975. this.trigger = triggerOptions.trigger;
  51976. this._triggerParameter = triggerOptions.parameter;
  51977. }
  51978. else {
  51979. this.trigger = triggerOptions;
  51980. }
  51981. this._nextActiveAction = this;
  51982. this._condition = condition;
  51983. }
  51984. /**
  51985. * Internal only
  51986. * @hidden
  51987. */
  51988. Action.prototype._prepare = function () {
  51989. };
  51990. /**
  51991. * Gets the trigger parameters
  51992. * @returns the trigger parameters
  51993. */
  51994. Action.prototype.getTriggerParameter = function () {
  51995. return this._triggerParameter;
  51996. };
  51997. /**
  51998. * Internal only - executes current action event
  51999. * @hidden
  52000. */
  52001. Action.prototype._executeCurrent = function (evt) {
  52002. if (this._nextActiveAction._condition) {
  52003. var condition = this._nextActiveAction._condition;
  52004. var currentRenderId = this._actionManager.getScene().getRenderId();
  52005. // We cache the current evaluation for the current frame
  52006. if (condition._evaluationId === currentRenderId) {
  52007. if (!condition._currentResult) {
  52008. return;
  52009. }
  52010. }
  52011. else {
  52012. condition._evaluationId = currentRenderId;
  52013. if (!condition.isValid()) {
  52014. condition._currentResult = false;
  52015. return;
  52016. }
  52017. condition._currentResult = true;
  52018. }
  52019. }
  52020. this.onBeforeExecuteObservable.notifyObservers(this);
  52021. this._nextActiveAction.execute(evt);
  52022. this.skipToNextActiveAction();
  52023. };
  52024. /**
  52025. * Execute placeholder for child classes
  52026. * @param evt optional action event
  52027. */
  52028. Action.prototype.execute = function (evt) {
  52029. };
  52030. /**
  52031. * Skips to next active action
  52032. */
  52033. Action.prototype.skipToNextActiveAction = function () {
  52034. if (this._nextActiveAction._child) {
  52035. if (!this._nextActiveAction._child._actionManager) {
  52036. this._nextActiveAction._child._actionManager = this._actionManager;
  52037. }
  52038. this._nextActiveAction = this._nextActiveAction._child;
  52039. }
  52040. else {
  52041. this._nextActiveAction = this;
  52042. }
  52043. };
  52044. /**
  52045. * Adds action to chain of actions, may be a DoNothingAction
  52046. * @param action defines the next action to execute
  52047. * @returns The action passed in
  52048. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52049. */
  52050. Action.prototype.then = function (action) {
  52051. this._child = action;
  52052. action._actionManager = this._actionManager;
  52053. action._prepare();
  52054. return action;
  52055. };
  52056. /**
  52057. * Internal only
  52058. * @hidden
  52059. */
  52060. Action.prototype._getProperty = function (propertyPath) {
  52061. return this._actionManager._getProperty(propertyPath);
  52062. };
  52063. /**
  52064. * Internal only
  52065. * @hidden
  52066. */
  52067. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52068. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52069. };
  52070. /**
  52071. * Serialize placeholder for child classes
  52072. * @param parent of child
  52073. * @returns the serialized object
  52074. */
  52075. Action.prototype.serialize = function (parent) {
  52076. };
  52077. /**
  52078. * Internal only called by serialize
  52079. * @hidden
  52080. */
  52081. Action.prototype._serialize = function (serializedAction, parent) {
  52082. var serializationObject = {
  52083. type: 1,
  52084. children: [],
  52085. name: serializedAction.name,
  52086. properties: serializedAction.properties || []
  52087. };
  52088. // Serialize child
  52089. if (this._child) {
  52090. this._child.serialize(serializationObject);
  52091. }
  52092. // Check if "this" has a condition
  52093. if (this._condition) {
  52094. var serializedCondition = this._condition.serialize();
  52095. serializedCondition.children.push(serializationObject);
  52096. if (parent) {
  52097. parent.children.push(serializedCondition);
  52098. }
  52099. return serializedCondition;
  52100. }
  52101. if (parent) {
  52102. parent.children.push(serializationObject);
  52103. }
  52104. return serializationObject;
  52105. };
  52106. /**
  52107. * Internal only
  52108. * @hidden
  52109. */
  52110. Action._SerializeValueAsString = function (value) {
  52111. if (typeof value === "number") {
  52112. return value.toString();
  52113. }
  52114. if (typeof value === "boolean") {
  52115. return value ? "true" : "false";
  52116. }
  52117. if (value instanceof BABYLON.Vector2) {
  52118. return value.x + ", " + value.y;
  52119. }
  52120. if (value instanceof BABYLON.Vector3) {
  52121. return value.x + ", " + value.y + ", " + value.z;
  52122. }
  52123. if (value instanceof BABYLON.Color3) {
  52124. return value.r + ", " + value.g + ", " + value.b;
  52125. }
  52126. if (value instanceof BABYLON.Color4) {
  52127. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52128. }
  52129. return value; // string
  52130. };
  52131. /**
  52132. * Internal only
  52133. * @hidden
  52134. */
  52135. Action._GetTargetProperty = function (target) {
  52136. return {
  52137. name: "target",
  52138. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52139. : target instanceof BABYLON.Light ? "LightProperties"
  52140. : target instanceof BABYLON.Camera ? "CameraProperties"
  52141. : "SceneProperties",
  52142. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52143. };
  52144. };
  52145. return Action;
  52146. }());
  52147. BABYLON.Action = Action;
  52148. })(BABYLON || (BABYLON = {}));
  52149. //# sourceMappingURL=babylon.action.js.map
  52150. var BABYLON;
  52151. (function (BABYLON) {
  52152. /**
  52153. * ActionEvent is the event being sent when an action is triggered.
  52154. */
  52155. var ActionEvent = /** @class */ (function () {
  52156. /**
  52157. * Creates a new ActionEvent
  52158. * @param source The mesh or sprite that triggered the action
  52159. * @param pointerX The X mouse cursor position at the time of the event
  52160. * @param pointerY The Y mouse cursor position at the time of the event
  52161. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52162. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52163. * @param additionalData additional data for the event
  52164. */
  52165. function ActionEvent(
  52166. /** The mesh or sprite that triggered the action */
  52167. source,
  52168. /** The X mouse cursor position at the time of the event */
  52169. pointerX,
  52170. /** The Y mouse cursor position at the time of the event */
  52171. pointerY,
  52172. /** The mesh that is currently pointed at (can be null) */
  52173. meshUnderPointer,
  52174. /** the original (browser) event that triggered the ActionEvent */
  52175. sourceEvent,
  52176. /** additional data for the event */
  52177. additionalData) {
  52178. this.source = source;
  52179. this.pointerX = pointerX;
  52180. this.pointerY = pointerY;
  52181. this.meshUnderPointer = meshUnderPointer;
  52182. this.sourceEvent = sourceEvent;
  52183. this.additionalData = additionalData;
  52184. }
  52185. /**
  52186. * Helper function to auto-create an ActionEvent from a source mesh.
  52187. * @param source The source mesh that triggered the event
  52188. * @param evt The original (browser) event
  52189. * @param additionalData additional data for the event
  52190. * @returns the new ActionEvent
  52191. */
  52192. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52193. var scene = source.getScene();
  52194. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52195. };
  52196. /**
  52197. * Helper function to auto-create an ActionEvent from a source sprite
  52198. * @param source The source sprite that triggered the event
  52199. * @param scene Scene associated with the sprite
  52200. * @param evt The original (browser) event
  52201. * @param additionalData additional data for the event
  52202. * @returns the new ActionEvent
  52203. */
  52204. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52205. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52206. };
  52207. /**
  52208. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52209. * @param scene the scene where the event occurred
  52210. * @param evt The original (browser) event
  52211. * @returns the new ActionEvent
  52212. */
  52213. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52214. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52215. };
  52216. /**
  52217. * Helper function to auto-create an ActionEvent from a primitive
  52218. * @param prim defines the target primitive
  52219. * @param pointerPos defines the pointer position
  52220. * @param evt The original (browser) event
  52221. * @param additionalData additional data for the event
  52222. * @returns the new ActionEvent
  52223. */
  52224. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52225. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52226. };
  52227. return ActionEvent;
  52228. }());
  52229. BABYLON.ActionEvent = ActionEvent;
  52230. /**
  52231. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52232. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52233. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52234. */
  52235. var ActionManager = /** @class */ (function () {
  52236. /**
  52237. * Creates a new action manager
  52238. * @param scene defines the hosting scene
  52239. */
  52240. function ActionManager(scene) {
  52241. // Members
  52242. /** Gets the list of actions */
  52243. this.actions = new Array();
  52244. /** Gets the cursor to use when hovering items */
  52245. this.hoverCursor = '';
  52246. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52247. scene._actionManagers.push(this);
  52248. }
  52249. Object.defineProperty(ActionManager, "NothingTrigger", {
  52250. /**
  52251. * Nothing
  52252. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52253. */
  52254. get: function () {
  52255. return ActionManager._NothingTrigger;
  52256. },
  52257. enumerable: true,
  52258. configurable: true
  52259. });
  52260. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52261. /**
  52262. * On pick
  52263. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52264. */
  52265. get: function () {
  52266. return ActionManager._OnPickTrigger;
  52267. },
  52268. enumerable: true,
  52269. configurable: true
  52270. });
  52271. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52272. /**
  52273. * On left pick
  52274. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52275. */
  52276. get: function () {
  52277. return ActionManager._OnLeftPickTrigger;
  52278. },
  52279. enumerable: true,
  52280. configurable: true
  52281. });
  52282. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52283. /**
  52284. * On right pick
  52285. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52286. */
  52287. get: function () {
  52288. return ActionManager._OnRightPickTrigger;
  52289. },
  52290. enumerable: true,
  52291. configurable: true
  52292. });
  52293. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52294. /**
  52295. * On center pick
  52296. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52297. */
  52298. get: function () {
  52299. return ActionManager._OnCenterPickTrigger;
  52300. },
  52301. enumerable: true,
  52302. configurable: true
  52303. });
  52304. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52305. /**
  52306. * On pick down
  52307. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52308. */
  52309. get: function () {
  52310. return ActionManager._OnPickDownTrigger;
  52311. },
  52312. enumerable: true,
  52313. configurable: true
  52314. });
  52315. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52316. /**
  52317. * On double pick
  52318. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52319. */
  52320. get: function () {
  52321. return ActionManager._OnDoublePickTrigger;
  52322. },
  52323. enumerable: true,
  52324. configurable: true
  52325. });
  52326. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52327. /**
  52328. * On pick up
  52329. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52330. */
  52331. get: function () {
  52332. return ActionManager._OnPickUpTrigger;
  52333. },
  52334. enumerable: true,
  52335. configurable: true
  52336. });
  52337. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52338. /**
  52339. * On pick out.
  52340. * This trigger will only be raised if you also declared a OnPickDown
  52341. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52342. */
  52343. get: function () {
  52344. return ActionManager._OnPickOutTrigger;
  52345. },
  52346. enumerable: true,
  52347. configurable: true
  52348. });
  52349. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52350. /**
  52351. * On long press
  52352. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52353. */
  52354. get: function () {
  52355. return ActionManager._OnLongPressTrigger;
  52356. },
  52357. enumerable: true,
  52358. configurable: true
  52359. });
  52360. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52361. /**
  52362. * On pointer over
  52363. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52364. */
  52365. get: function () {
  52366. return ActionManager._OnPointerOverTrigger;
  52367. },
  52368. enumerable: true,
  52369. configurable: true
  52370. });
  52371. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52372. /**
  52373. * On pointer out
  52374. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52375. */
  52376. get: function () {
  52377. return ActionManager._OnPointerOutTrigger;
  52378. },
  52379. enumerable: true,
  52380. configurable: true
  52381. });
  52382. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52383. /**
  52384. * On every frame
  52385. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52386. */
  52387. get: function () {
  52388. return ActionManager._OnEveryFrameTrigger;
  52389. },
  52390. enumerable: true,
  52391. configurable: true
  52392. });
  52393. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52394. /**
  52395. * On intersection enter
  52396. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52397. */
  52398. get: function () {
  52399. return ActionManager._OnIntersectionEnterTrigger;
  52400. },
  52401. enumerable: true,
  52402. configurable: true
  52403. });
  52404. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52405. /**
  52406. * On intersection exit
  52407. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52408. */
  52409. get: function () {
  52410. return ActionManager._OnIntersectionExitTrigger;
  52411. },
  52412. enumerable: true,
  52413. configurable: true
  52414. });
  52415. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52416. /**
  52417. * On key down
  52418. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52419. */
  52420. get: function () {
  52421. return ActionManager._OnKeyDownTrigger;
  52422. },
  52423. enumerable: true,
  52424. configurable: true
  52425. });
  52426. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52427. /**
  52428. * On key up
  52429. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52430. */
  52431. get: function () {
  52432. return ActionManager._OnKeyUpTrigger;
  52433. },
  52434. enumerable: true,
  52435. configurable: true
  52436. });
  52437. // Methods
  52438. /**
  52439. * Releases all associated resources
  52440. */
  52441. ActionManager.prototype.dispose = function () {
  52442. var index = this._scene._actionManagers.indexOf(this);
  52443. for (var i = 0; i < this.actions.length; i++) {
  52444. var action = this.actions[i];
  52445. ActionManager.Triggers[action.trigger]--;
  52446. if (ActionManager.Triggers[action.trigger] === 0) {
  52447. delete ActionManager.Triggers[action.trigger];
  52448. }
  52449. }
  52450. if (index > -1) {
  52451. this._scene._actionManagers.splice(index, 1);
  52452. }
  52453. };
  52454. /**
  52455. * Gets hosting scene
  52456. * @returns the hosting scene
  52457. */
  52458. ActionManager.prototype.getScene = function () {
  52459. return this._scene;
  52460. };
  52461. /**
  52462. * Does this action manager handles actions of any of the given triggers
  52463. * @param triggers defines the triggers to be tested
  52464. * @return a boolean indicating whether one (or more) of the triggers is handled
  52465. */
  52466. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52467. for (var index = 0; index < this.actions.length; index++) {
  52468. var action = this.actions[index];
  52469. if (triggers.indexOf(action.trigger) > -1) {
  52470. return true;
  52471. }
  52472. }
  52473. return false;
  52474. };
  52475. /**
  52476. * Does this action manager handles actions of a given trigger
  52477. * @param trigger defines the trigger to be tested
  52478. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52479. * @return whether the trigger is handled
  52480. */
  52481. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52482. for (var index = 0; index < this.actions.length; index++) {
  52483. var action = this.actions[index];
  52484. if (action.trigger === trigger) {
  52485. if (parameterPredicate) {
  52486. if (parameterPredicate(action.getTriggerParameter())) {
  52487. return true;
  52488. }
  52489. }
  52490. else {
  52491. return true;
  52492. }
  52493. }
  52494. }
  52495. return false;
  52496. };
  52497. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52498. /**
  52499. * Does this action manager has pointer triggers
  52500. */
  52501. get: function () {
  52502. for (var index = 0; index < this.actions.length; index++) {
  52503. var action = this.actions[index];
  52504. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52505. return true;
  52506. }
  52507. }
  52508. return false;
  52509. },
  52510. enumerable: true,
  52511. configurable: true
  52512. });
  52513. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52514. /**
  52515. * Does this action manager has pick triggers
  52516. */
  52517. get: function () {
  52518. for (var index = 0; index < this.actions.length; index++) {
  52519. var action = this.actions[index];
  52520. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52521. return true;
  52522. }
  52523. }
  52524. return false;
  52525. },
  52526. enumerable: true,
  52527. configurable: true
  52528. });
  52529. Object.defineProperty(ActionManager, "HasTriggers", {
  52530. /**
  52531. * Does exist one action manager with at least one trigger
  52532. **/
  52533. get: function () {
  52534. for (var t in ActionManager.Triggers) {
  52535. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52536. return true;
  52537. }
  52538. }
  52539. return false;
  52540. },
  52541. enumerable: true,
  52542. configurable: true
  52543. });
  52544. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52545. /**
  52546. * Does exist one action manager with at least one pick trigger
  52547. **/
  52548. get: function () {
  52549. for (var t in ActionManager.Triggers) {
  52550. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52551. var t_int = parseInt(t);
  52552. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52553. return true;
  52554. }
  52555. }
  52556. }
  52557. return false;
  52558. },
  52559. enumerable: true,
  52560. configurable: true
  52561. });
  52562. /**
  52563. * Does exist one action manager that handles actions of a given trigger
  52564. * @param trigger defines the trigger to be tested
  52565. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52566. **/
  52567. ActionManager.HasSpecificTrigger = function (trigger) {
  52568. for (var t in ActionManager.Triggers) {
  52569. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52570. var t_int = parseInt(t);
  52571. if (t_int === trigger) {
  52572. return true;
  52573. }
  52574. }
  52575. }
  52576. return false;
  52577. };
  52578. /**
  52579. * Registers an action to this action manager
  52580. * @param action defines the action to be registered
  52581. * @return the action amended (prepared) after registration
  52582. */
  52583. ActionManager.prototype.registerAction = function (action) {
  52584. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52585. if (this.getScene().actionManager !== this) {
  52586. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52587. return null;
  52588. }
  52589. }
  52590. this.actions.push(action);
  52591. if (ActionManager.Triggers[action.trigger]) {
  52592. ActionManager.Triggers[action.trigger]++;
  52593. }
  52594. else {
  52595. ActionManager.Triggers[action.trigger] = 1;
  52596. }
  52597. action._actionManager = this;
  52598. action._prepare();
  52599. return action;
  52600. };
  52601. /**
  52602. * Unregisters an action to this action manager
  52603. * @param action defines the action to be unregistered
  52604. * @return a boolean indicating whether the action has been unregistered
  52605. */
  52606. ActionManager.prototype.unregisterAction = function (action) {
  52607. var index = this.actions.indexOf(action);
  52608. if (index !== -1) {
  52609. this.actions.splice(index, 1);
  52610. ActionManager.Triggers[action.trigger] -= 1;
  52611. if (ActionManager.Triggers[action.trigger] === 0) {
  52612. delete ActionManager.Triggers[action.trigger];
  52613. }
  52614. delete action._actionManager;
  52615. return true;
  52616. }
  52617. return false;
  52618. };
  52619. /**
  52620. * Process a specific trigger
  52621. * @param trigger defines the trigger to process
  52622. * @param evt defines the event details to be processed
  52623. */
  52624. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52625. for (var index = 0; index < this.actions.length; index++) {
  52626. var action = this.actions[index];
  52627. if (action.trigger === trigger) {
  52628. if (evt) {
  52629. if (trigger === ActionManager.OnKeyUpTrigger
  52630. || trigger === ActionManager.OnKeyDownTrigger) {
  52631. var parameter = action.getTriggerParameter();
  52632. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52633. if (!parameter.toLowerCase) {
  52634. continue;
  52635. }
  52636. var lowerCase = parameter.toLowerCase();
  52637. if (lowerCase !== evt.sourceEvent.key) {
  52638. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52639. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52640. if (actualkey !== lowerCase) {
  52641. continue;
  52642. }
  52643. }
  52644. }
  52645. }
  52646. }
  52647. action._executeCurrent(evt);
  52648. }
  52649. }
  52650. };
  52651. /** @hidden */
  52652. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52653. var properties = propertyPath.split(".");
  52654. for (var index = 0; index < properties.length - 1; index++) {
  52655. target = target[properties[index]];
  52656. }
  52657. return target;
  52658. };
  52659. /** @hidden */
  52660. ActionManager.prototype._getProperty = function (propertyPath) {
  52661. var properties = propertyPath.split(".");
  52662. return properties[properties.length - 1];
  52663. };
  52664. /**
  52665. * Serialize this manager to a JSON object
  52666. * @param name defines the property name to store this manager
  52667. * @returns a JSON representation of this manager
  52668. */
  52669. ActionManager.prototype.serialize = function (name) {
  52670. var root = {
  52671. children: new Array(),
  52672. name: name,
  52673. type: 3,
  52674. properties: new Array() // Empty for root but required
  52675. };
  52676. for (var i = 0; i < this.actions.length; i++) {
  52677. var triggerObject = {
  52678. type: 0,
  52679. children: new Array(),
  52680. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52681. properties: new Array()
  52682. };
  52683. var triggerOptions = this.actions[i].triggerOptions;
  52684. if (triggerOptions && typeof triggerOptions !== "number") {
  52685. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52686. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52687. }
  52688. else {
  52689. var parameter = {};
  52690. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52691. if (triggerOptions.parameter.mesh) {
  52692. parameter._meshId = triggerOptions.parameter.mesh.id;
  52693. }
  52694. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52695. }
  52696. }
  52697. // Serialize child action, recursively
  52698. this.actions[i].serialize(triggerObject);
  52699. // Add serialized trigger
  52700. root.children.push(triggerObject);
  52701. }
  52702. return root;
  52703. };
  52704. /**
  52705. * Creates a new ActionManager from a JSON data
  52706. * @param parsedActions defines the JSON data to read from
  52707. * @param object defines the hosting mesh
  52708. * @param scene defines the hosting scene
  52709. */
  52710. ActionManager.Parse = function (parsedActions, object, scene) {
  52711. var actionManager = new ActionManager(scene);
  52712. if (object === null)
  52713. scene.actionManager = actionManager;
  52714. else
  52715. object.actionManager = actionManager;
  52716. // instanciate a new object
  52717. var instanciate = function (name, params) {
  52718. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52719. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52720. newInstance.constructor.apply(newInstance, params);
  52721. return newInstance;
  52722. };
  52723. var parseParameter = function (name, value, target, propertyPath) {
  52724. if (propertyPath === null) {
  52725. // String, boolean or float
  52726. var floatValue = parseFloat(value);
  52727. if (value === "true" || value === "false")
  52728. return value === "true";
  52729. else
  52730. return isNaN(floatValue) ? value : floatValue;
  52731. }
  52732. var effectiveTarget = propertyPath.split(".");
  52733. var values = value.split(",");
  52734. // Get effective Target
  52735. for (var i = 0; i < effectiveTarget.length; i++) {
  52736. target = target[effectiveTarget[i]];
  52737. }
  52738. // Return appropriate value with its type
  52739. if (typeof (target) === "boolean")
  52740. return values[0] === "true";
  52741. if (typeof (target) === "string")
  52742. return values[0];
  52743. // Parameters with multiple values such as Vector3 etc.
  52744. var split = new Array();
  52745. for (var i = 0; i < values.length; i++)
  52746. split.push(parseFloat(values[i]));
  52747. if (target instanceof BABYLON.Vector3)
  52748. return BABYLON.Vector3.FromArray(split);
  52749. if (target instanceof BABYLON.Vector4)
  52750. return BABYLON.Vector4.FromArray(split);
  52751. if (target instanceof BABYLON.Color3)
  52752. return BABYLON.Color3.FromArray(split);
  52753. if (target instanceof BABYLON.Color4)
  52754. return BABYLON.Color4.FromArray(split);
  52755. return parseFloat(values[0]);
  52756. };
  52757. // traverse graph per trigger
  52758. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52759. if (combineArray === void 0) { combineArray = null; }
  52760. if (parsedAction.detached)
  52761. return;
  52762. var parameters = new Array();
  52763. var target = null;
  52764. var propertyPath = null;
  52765. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52766. // Parameters
  52767. if (parsedAction.type === 2)
  52768. parameters.push(actionManager);
  52769. else
  52770. parameters.push(trigger);
  52771. if (combine) {
  52772. var actions = new Array();
  52773. for (var j = 0; j < parsedAction.combine.length; j++) {
  52774. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52775. }
  52776. parameters.push(actions);
  52777. }
  52778. else {
  52779. for (var i = 0; i < parsedAction.properties.length; i++) {
  52780. var value = parsedAction.properties[i].value;
  52781. var name = parsedAction.properties[i].name;
  52782. var targetType = parsedAction.properties[i].targetType;
  52783. if (name === "target")
  52784. if (targetType !== null && targetType === "SceneProperties")
  52785. value = target = scene;
  52786. else
  52787. value = target = scene.getNodeByName(value);
  52788. else if (name === "parent")
  52789. value = scene.getNodeByName(value);
  52790. else if (name === "sound")
  52791. value = scene.getSoundByName(value);
  52792. else if (name !== "propertyPath") {
  52793. if (parsedAction.type === 2 && name === "operator")
  52794. value = BABYLON.ValueCondition[value];
  52795. else
  52796. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52797. }
  52798. else {
  52799. propertyPath = value;
  52800. }
  52801. parameters.push(value);
  52802. }
  52803. }
  52804. if (combineArray === null) {
  52805. parameters.push(condition);
  52806. }
  52807. else {
  52808. parameters.push(null);
  52809. }
  52810. // If interpolate value action
  52811. if (parsedAction.name === "InterpolateValueAction") {
  52812. var param = parameters[parameters.length - 2];
  52813. parameters[parameters.length - 1] = param;
  52814. parameters[parameters.length - 2] = condition;
  52815. }
  52816. // Action or condition(s) and not CombineAction
  52817. var newAction = instanciate(parsedAction.name, parameters);
  52818. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52819. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52820. if (action)
  52821. action.then(nothing);
  52822. else
  52823. actionManager.registerAction(nothing);
  52824. action = nothing;
  52825. }
  52826. if (combineArray === null) {
  52827. if (newAction instanceof BABYLON.Condition) {
  52828. condition = newAction;
  52829. newAction = action;
  52830. }
  52831. else {
  52832. condition = null;
  52833. if (action)
  52834. action.then(newAction);
  52835. else
  52836. actionManager.registerAction(newAction);
  52837. }
  52838. }
  52839. else {
  52840. combineArray.push(newAction);
  52841. }
  52842. for (var i = 0; i < parsedAction.children.length; i++)
  52843. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52844. };
  52845. // triggers
  52846. for (var i = 0; i < parsedActions.children.length; i++) {
  52847. var triggerParams;
  52848. var trigger = parsedActions.children[i];
  52849. if (trigger.properties.length > 0) {
  52850. var param = trigger.properties[0].value;
  52851. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52852. if (value._meshId) {
  52853. value.mesh = scene.getMeshByID(value._meshId);
  52854. }
  52855. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52856. }
  52857. else
  52858. triggerParams = ActionManager[trigger.name];
  52859. for (var j = 0; j < trigger.children.length; j++) {
  52860. if (!trigger.detached)
  52861. traverse(trigger.children[j], triggerParams, null, null);
  52862. }
  52863. }
  52864. };
  52865. /**
  52866. * Get a trigger name by index
  52867. * @param trigger defines the trigger index
  52868. * @returns a trigger name
  52869. */
  52870. ActionManager.GetTriggerName = function (trigger) {
  52871. switch (trigger) {
  52872. case 0: return "NothingTrigger";
  52873. case 1: return "OnPickTrigger";
  52874. case 2: return "OnLeftPickTrigger";
  52875. case 3: return "OnRightPickTrigger";
  52876. case 4: return "OnCenterPickTrigger";
  52877. case 5: return "OnPickDownTrigger";
  52878. case 6: return "OnPickUpTrigger";
  52879. case 7: return "OnLongPressTrigger";
  52880. case 8: return "OnPointerOverTrigger";
  52881. case 9: return "OnPointerOutTrigger";
  52882. case 10: return "OnEveryFrameTrigger";
  52883. case 11: return "OnIntersectionEnterTrigger";
  52884. case 12: return "OnIntersectionExitTrigger";
  52885. case 13: return "OnKeyDownTrigger";
  52886. case 14: return "OnKeyUpTrigger";
  52887. case 15: return "OnPickOutTrigger";
  52888. default: return "";
  52889. }
  52890. };
  52891. // Statics
  52892. ActionManager._NothingTrigger = 0;
  52893. ActionManager._OnPickTrigger = 1;
  52894. ActionManager._OnLeftPickTrigger = 2;
  52895. ActionManager._OnRightPickTrigger = 3;
  52896. ActionManager._OnCenterPickTrigger = 4;
  52897. ActionManager._OnPickDownTrigger = 5;
  52898. ActionManager._OnDoublePickTrigger = 6;
  52899. ActionManager._OnPickUpTrigger = 7;
  52900. ActionManager._OnLongPressTrigger = 8;
  52901. ActionManager._OnPointerOverTrigger = 9;
  52902. ActionManager._OnPointerOutTrigger = 10;
  52903. ActionManager._OnEveryFrameTrigger = 11;
  52904. ActionManager._OnIntersectionEnterTrigger = 12;
  52905. ActionManager._OnIntersectionExitTrigger = 13;
  52906. ActionManager._OnKeyDownTrigger = 14;
  52907. ActionManager._OnKeyUpTrigger = 15;
  52908. ActionManager._OnPickOutTrigger = 16;
  52909. /** Gets the list of active triggers */
  52910. ActionManager.Triggers = {};
  52911. return ActionManager;
  52912. }());
  52913. BABYLON.ActionManager = ActionManager;
  52914. })(BABYLON || (BABYLON = {}));
  52915. //# sourceMappingURL=babylon.actionManager.js.map
  52916. var BABYLON;
  52917. (function (BABYLON) {
  52918. var InterpolateValueAction = /** @class */ (function (_super) {
  52919. __extends(InterpolateValueAction, _super);
  52920. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52921. if (duration === void 0) { duration = 1000; }
  52922. var _this = _super.call(this, triggerOptions, condition) || this;
  52923. _this.propertyPath = propertyPath;
  52924. _this.value = value;
  52925. _this.duration = duration;
  52926. _this.stopOtherAnimations = stopOtherAnimations;
  52927. _this.onInterpolationDone = onInterpolationDone;
  52928. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52929. _this._target = _this._effectiveTarget = target;
  52930. return _this;
  52931. }
  52932. InterpolateValueAction.prototype._prepare = function () {
  52933. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52934. this._property = this._getProperty(this.propertyPath);
  52935. };
  52936. InterpolateValueAction.prototype.execute = function () {
  52937. var _this = this;
  52938. var scene = this._actionManager.getScene();
  52939. var keys = [
  52940. {
  52941. frame: 0,
  52942. value: this._effectiveTarget[this._property]
  52943. }, {
  52944. frame: 100,
  52945. value: this.value
  52946. }
  52947. ];
  52948. var dataType;
  52949. if (typeof this.value === "number") {
  52950. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52951. }
  52952. else if (this.value instanceof BABYLON.Color3) {
  52953. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52954. }
  52955. else if (this.value instanceof BABYLON.Vector3) {
  52956. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52957. }
  52958. else if (this.value instanceof BABYLON.Matrix) {
  52959. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52960. }
  52961. else if (this.value instanceof BABYLON.Quaternion) {
  52962. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52963. }
  52964. else {
  52965. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52966. return;
  52967. }
  52968. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52969. animation.setKeys(keys);
  52970. if (this.stopOtherAnimations) {
  52971. scene.stopAnimation(this._effectiveTarget);
  52972. }
  52973. var wrapper = function () {
  52974. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52975. if (_this.onInterpolationDone) {
  52976. _this.onInterpolationDone();
  52977. }
  52978. };
  52979. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52980. };
  52981. InterpolateValueAction.prototype.serialize = function (parent) {
  52982. return _super.prototype._serialize.call(this, {
  52983. name: "InterpolateValueAction",
  52984. properties: [
  52985. BABYLON.Action._GetTargetProperty(this._target),
  52986. { name: "propertyPath", value: this.propertyPath },
  52987. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52988. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52989. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52990. ]
  52991. }, parent);
  52992. };
  52993. return InterpolateValueAction;
  52994. }(BABYLON.Action));
  52995. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52996. })(BABYLON || (BABYLON = {}));
  52997. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52998. var BABYLON;
  52999. (function (BABYLON) {
  53000. var SwitchBooleanAction = /** @class */ (function (_super) {
  53001. __extends(SwitchBooleanAction, _super);
  53002. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53003. var _this = _super.call(this, triggerOptions, condition) || this;
  53004. _this.propertyPath = propertyPath;
  53005. _this._target = _this._effectiveTarget = target;
  53006. return _this;
  53007. }
  53008. SwitchBooleanAction.prototype._prepare = function () {
  53009. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53010. this._property = this._getProperty(this.propertyPath);
  53011. };
  53012. SwitchBooleanAction.prototype.execute = function () {
  53013. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53014. };
  53015. SwitchBooleanAction.prototype.serialize = function (parent) {
  53016. return _super.prototype._serialize.call(this, {
  53017. name: "SwitchBooleanAction",
  53018. properties: [
  53019. BABYLON.Action._GetTargetProperty(this._target),
  53020. { name: "propertyPath", value: this.propertyPath }
  53021. ]
  53022. }, parent);
  53023. };
  53024. return SwitchBooleanAction;
  53025. }(BABYLON.Action));
  53026. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53027. var SetStateAction = /** @class */ (function (_super) {
  53028. __extends(SetStateAction, _super);
  53029. function SetStateAction(triggerOptions, target, value, condition) {
  53030. var _this = _super.call(this, triggerOptions, condition) || this;
  53031. _this.value = value;
  53032. _this._target = target;
  53033. return _this;
  53034. }
  53035. SetStateAction.prototype.execute = function () {
  53036. this._target.state = this.value;
  53037. };
  53038. SetStateAction.prototype.serialize = function (parent) {
  53039. return _super.prototype._serialize.call(this, {
  53040. name: "SetStateAction",
  53041. properties: [
  53042. BABYLON.Action._GetTargetProperty(this._target),
  53043. { name: "value", value: this.value }
  53044. ]
  53045. }, parent);
  53046. };
  53047. return SetStateAction;
  53048. }(BABYLON.Action));
  53049. BABYLON.SetStateAction = SetStateAction;
  53050. var SetValueAction = /** @class */ (function (_super) {
  53051. __extends(SetValueAction, _super);
  53052. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53053. var _this = _super.call(this, triggerOptions, condition) || this;
  53054. _this.propertyPath = propertyPath;
  53055. _this.value = value;
  53056. _this._target = _this._effectiveTarget = target;
  53057. return _this;
  53058. }
  53059. SetValueAction.prototype._prepare = function () {
  53060. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53061. this._property = this._getProperty(this.propertyPath);
  53062. };
  53063. SetValueAction.prototype.execute = function () {
  53064. this._effectiveTarget[this._property] = this.value;
  53065. if (this._target.markAsDirty) {
  53066. this._target.markAsDirty(this._property);
  53067. }
  53068. };
  53069. SetValueAction.prototype.serialize = function (parent) {
  53070. return _super.prototype._serialize.call(this, {
  53071. name: "SetValueAction",
  53072. properties: [
  53073. BABYLON.Action._GetTargetProperty(this._target),
  53074. { name: "propertyPath", value: this.propertyPath },
  53075. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53076. ]
  53077. }, parent);
  53078. };
  53079. return SetValueAction;
  53080. }(BABYLON.Action));
  53081. BABYLON.SetValueAction = SetValueAction;
  53082. var IncrementValueAction = /** @class */ (function (_super) {
  53083. __extends(IncrementValueAction, _super);
  53084. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53085. var _this = _super.call(this, triggerOptions, condition) || this;
  53086. _this.propertyPath = propertyPath;
  53087. _this.value = value;
  53088. _this._target = _this._effectiveTarget = target;
  53089. return _this;
  53090. }
  53091. IncrementValueAction.prototype._prepare = function () {
  53092. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53093. this._property = this._getProperty(this.propertyPath);
  53094. if (typeof this._effectiveTarget[this._property] !== "number") {
  53095. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53096. }
  53097. };
  53098. IncrementValueAction.prototype.execute = function () {
  53099. this._effectiveTarget[this._property] += this.value;
  53100. if (this._target.markAsDirty) {
  53101. this._target.markAsDirty(this._property);
  53102. }
  53103. };
  53104. IncrementValueAction.prototype.serialize = function (parent) {
  53105. return _super.prototype._serialize.call(this, {
  53106. name: "IncrementValueAction",
  53107. properties: [
  53108. BABYLON.Action._GetTargetProperty(this._target),
  53109. { name: "propertyPath", value: this.propertyPath },
  53110. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53111. ]
  53112. }, parent);
  53113. };
  53114. return IncrementValueAction;
  53115. }(BABYLON.Action));
  53116. BABYLON.IncrementValueAction = IncrementValueAction;
  53117. var PlayAnimationAction = /** @class */ (function (_super) {
  53118. __extends(PlayAnimationAction, _super);
  53119. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53120. var _this = _super.call(this, triggerOptions, condition) || this;
  53121. _this.from = from;
  53122. _this.to = to;
  53123. _this.loop = loop;
  53124. _this._target = target;
  53125. return _this;
  53126. }
  53127. PlayAnimationAction.prototype._prepare = function () {
  53128. };
  53129. PlayAnimationAction.prototype.execute = function () {
  53130. var scene = this._actionManager.getScene();
  53131. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53132. };
  53133. PlayAnimationAction.prototype.serialize = function (parent) {
  53134. return _super.prototype._serialize.call(this, {
  53135. name: "PlayAnimationAction",
  53136. properties: [
  53137. BABYLON.Action._GetTargetProperty(this._target),
  53138. { name: "from", value: String(this.from) },
  53139. { name: "to", value: String(this.to) },
  53140. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53141. ]
  53142. }, parent);
  53143. };
  53144. return PlayAnimationAction;
  53145. }(BABYLON.Action));
  53146. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53147. var StopAnimationAction = /** @class */ (function (_super) {
  53148. __extends(StopAnimationAction, _super);
  53149. function StopAnimationAction(triggerOptions, target, condition) {
  53150. var _this = _super.call(this, triggerOptions, condition) || this;
  53151. _this._target = target;
  53152. return _this;
  53153. }
  53154. StopAnimationAction.prototype._prepare = function () {
  53155. };
  53156. StopAnimationAction.prototype.execute = function () {
  53157. var scene = this._actionManager.getScene();
  53158. scene.stopAnimation(this._target);
  53159. };
  53160. StopAnimationAction.prototype.serialize = function (parent) {
  53161. return _super.prototype._serialize.call(this, {
  53162. name: "StopAnimationAction",
  53163. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53164. }, parent);
  53165. };
  53166. return StopAnimationAction;
  53167. }(BABYLON.Action));
  53168. BABYLON.StopAnimationAction = StopAnimationAction;
  53169. var DoNothingAction = /** @class */ (function (_super) {
  53170. __extends(DoNothingAction, _super);
  53171. function DoNothingAction(triggerOptions, condition) {
  53172. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53173. return _super.call(this, triggerOptions, condition) || this;
  53174. }
  53175. DoNothingAction.prototype.execute = function () {
  53176. };
  53177. DoNothingAction.prototype.serialize = function (parent) {
  53178. return _super.prototype._serialize.call(this, {
  53179. name: "DoNothingAction",
  53180. properties: []
  53181. }, parent);
  53182. };
  53183. return DoNothingAction;
  53184. }(BABYLON.Action));
  53185. BABYLON.DoNothingAction = DoNothingAction;
  53186. var CombineAction = /** @class */ (function (_super) {
  53187. __extends(CombineAction, _super);
  53188. function CombineAction(triggerOptions, children, condition) {
  53189. var _this = _super.call(this, triggerOptions, condition) || this;
  53190. _this.children = children;
  53191. return _this;
  53192. }
  53193. CombineAction.prototype._prepare = function () {
  53194. for (var index = 0; index < this.children.length; index++) {
  53195. this.children[index]._actionManager = this._actionManager;
  53196. this.children[index]._prepare();
  53197. }
  53198. };
  53199. CombineAction.prototype.execute = function (evt) {
  53200. for (var index = 0; index < this.children.length; index++) {
  53201. this.children[index].execute(evt);
  53202. }
  53203. };
  53204. CombineAction.prototype.serialize = function (parent) {
  53205. var serializationObject = _super.prototype._serialize.call(this, {
  53206. name: "CombineAction",
  53207. properties: [],
  53208. combine: []
  53209. }, parent);
  53210. for (var i = 0; i < this.children.length; i++) {
  53211. serializationObject.combine.push(this.children[i].serialize(null));
  53212. }
  53213. return serializationObject;
  53214. };
  53215. return CombineAction;
  53216. }(BABYLON.Action));
  53217. BABYLON.CombineAction = CombineAction;
  53218. var ExecuteCodeAction = /** @class */ (function (_super) {
  53219. __extends(ExecuteCodeAction, _super);
  53220. function ExecuteCodeAction(triggerOptions, func, condition) {
  53221. var _this = _super.call(this, triggerOptions, condition) || this;
  53222. _this.func = func;
  53223. return _this;
  53224. }
  53225. ExecuteCodeAction.prototype.execute = function (evt) {
  53226. this.func(evt);
  53227. };
  53228. return ExecuteCodeAction;
  53229. }(BABYLON.Action));
  53230. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53231. var SetParentAction = /** @class */ (function (_super) {
  53232. __extends(SetParentAction, _super);
  53233. function SetParentAction(triggerOptions, target, parent, condition) {
  53234. var _this = _super.call(this, triggerOptions, condition) || this;
  53235. _this._target = target;
  53236. _this._parent = parent;
  53237. return _this;
  53238. }
  53239. SetParentAction.prototype._prepare = function () {
  53240. };
  53241. SetParentAction.prototype.execute = function () {
  53242. if (this._target.parent === this._parent) {
  53243. return;
  53244. }
  53245. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53246. invertParentWorldMatrix.invert();
  53247. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53248. this._target.parent = this._parent;
  53249. };
  53250. SetParentAction.prototype.serialize = function (parent) {
  53251. return _super.prototype._serialize.call(this, {
  53252. name: "SetParentAction",
  53253. properties: [
  53254. BABYLON.Action._GetTargetProperty(this._target),
  53255. BABYLON.Action._GetTargetProperty(this._parent),
  53256. ]
  53257. }, parent);
  53258. };
  53259. return SetParentAction;
  53260. }(BABYLON.Action));
  53261. BABYLON.SetParentAction = SetParentAction;
  53262. var PlaySoundAction = /** @class */ (function (_super) {
  53263. __extends(PlaySoundAction, _super);
  53264. function PlaySoundAction(triggerOptions, sound, condition) {
  53265. var _this = _super.call(this, triggerOptions, condition) || this;
  53266. _this._sound = sound;
  53267. return _this;
  53268. }
  53269. PlaySoundAction.prototype._prepare = function () {
  53270. };
  53271. PlaySoundAction.prototype.execute = function () {
  53272. if (this._sound !== undefined)
  53273. this._sound.play();
  53274. };
  53275. PlaySoundAction.prototype.serialize = function (parent) {
  53276. return _super.prototype._serialize.call(this, {
  53277. name: "PlaySoundAction",
  53278. properties: [{ name: "sound", value: this._sound.name }]
  53279. }, parent);
  53280. };
  53281. return PlaySoundAction;
  53282. }(BABYLON.Action));
  53283. BABYLON.PlaySoundAction = PlaySoundAction;
  53284. var StopSoundAction = /** @class */ (function (_super) {
  53285. __extends(StopSoundAction, _super);
  53286. function StopSoundAction(triggerOptions, sound, condition) {
  53287. var _this = _super.call(this, triggerOptions, condition) || this;
  53288. _this._sound = sound;
  53289. return _this;
  53290. }
  53291. StopSoundAction.prototype._prepare = function () {
  53292. };
  53293. StopSoundAction.prototype.execute = function () {
  53294. if (this._sound !== undefined)
  53295. this._sound.stop();
  53296. };
  53297. StopSoundAction.prototype.serialize = function (parent) {
  53298. return _super.prototype._serialize.call(this, {
  53299. name: "StopSoundAction",
  53300. properties: [{ name: "sound", value: this._sound.name }]
  53301. }, parent);
  53302. };
  53303. return StopSoundAction;
  53304. }(BABYLON.Action));
  53305. BABYLON.StopSoundAction = StopSoundAction;
  53306. })(BABYLON || (BABYLON = {}));
  53307. //# sourceMappingURL=babylon.directActions.js.map
  53308. var BABYLON;
  53309. (function (BABYLON) {
  53310. var SpriteManager = /** @class */ (function () {
  53311. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53312. if (epsilon === void 0) { epsilon = 0.01; }
  53313. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53314. this.name = name;
  53315. this.sprites = new Array();
  53316. this.renderingGroupId = 0;
  53317. this.layerMask = 0x0FFFFFFF;
  53318. this.fogEnabled = true;
  53319. this.isPickable = false;
  53320. /**
  53321. * An event triggered when the manager is disposed.
  53322. */
  53323. this.onDisposeObservable = new BABYLON.Observable();
  53324. this._vertexBuffers = {};
  53325. this._capacity = capacity;
  53326. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53327. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53328. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53329. if (cellSize.width && cellSize.height) {
  53330. this.cellWidth = cellSize.width;
  53331. this.cellHeight = cellSize.height;
  53332. }
  53333. else if (cellSize !== undefined) {
  53334. this.cellWidth = cellSize;
  53335. this.cellHeight = cellSize;
  53336. }
  53337. else {
  53338. return;
  53339. }
  53340. this._epsilon = epsilon;
  53341. this._scene = scene;
  53342. this._scene.spriteManagers.push(this);
  53343. var indices = [];
  53344. var index = 0;
  53345. for (var count = 0; count < capacity; count++) {
  53346. indices.push(index);
  53347. indices.push(index + 1);
  53348. indices.push(index + 2);
  53349. indices.push(index);
  53350. indices.push(index + 2);
  53351. indices.push(index + 3);
  53352. index += 4;
  53353. }
  53354. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53355. // VBO
  53356. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53357. this._vertexData = new Float32Array(capacity * 16 * 4);
  53358. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53359. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53360. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53361. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53362. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53363. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53364. this._vertexBuffers["options"] = options;
  53365. this._vertexBuffers["cellInfo"] = cellInfo;
  53366. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53367. // Effects
  53368. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53369. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53370. }
  53371. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53372. set: function (callback) {
  53373. if (this._onDisposeObserver) {
  53374. this.onDisposeObservable.remove(this._onDisposeObserver);
  53375. }
  53376. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53377. },
  53378. enumerable: true,
  53379. configurable: true
  53380. });
  53381. Object.defineProperty(SpriteManager.prototype, "texture", {
  53382. get: function () {
  53383. return this._spriteTexture;
  53384. },
  53385. set: function (value) {
  53386. this._spriteTexture = value;
  53387. },
  53388. enumerable: true,
  53389. configurable: true
  53390. });
  53391. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53392. var arrayOffset = index * 16;
  53393. if (offsetX === 0)
  53394. offsetX = this._epsilon;
  53395. else if (offsetX === 1)
  53396. offsetX = 1 - this._epsilon;
  53397. if (offsetY === 0)
  53398. offsetY = this._epsilon;
  53399. else if (offsetY === 1)
  53400. offsetY = 1 - this._epsilon;
  53401. this._vertexData[arrayOffset] = sprite.position.x;
  53402. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53403. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53404. this._vertexData[arrayOffset + 3] = sprite.angle;
  53405. this._vertexData[arrayOffset + 4] = sprite.width;
  53406. this._vertexData[arrayOffset + 5] = sprite.height;
  53407. this._vertexData[arrayOffset + 6] = offsetX;
  53408. this._vertexData[arrayOffset + 7] = offsetY;
  53409. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53410. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53411. var offset = (sprite.cellIndex / rowSize) >> 0;
  53412. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53413. this._vertexData[arrayOffset + 11] = offset;
  53414. // Color
  53415. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53416. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53417. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53418. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53419. };
  53420. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53421. var count = Math.min(this._capacity, this.sprites.length);
  53422. var min = BABYLON.Vector3.Zero();
  53423. var max = BABYLON.Vector3.Zero();
  53424. var distance = Number.MAX_VALUE;
  53425. var currentSprite = null;
  53426. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53427. var cameraView = camera.getViewMatrix();
  53428. for (var index = 0; index < count; index++) {
  53429. var sprite = this.sprites[index];
  53430. if (!sprite) {
  53431. continue;
  53432. }
  53433. if (predicate) {
  53434. if (!predicate(sprite)) {
  53435. continue;
  53436. }
  53437. }
  53438. else if (!sprite.isPickable) {
  53439. continue;
  53440. }
  53441. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53442. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53443. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53444. if (ray.intersectsBoxMinMax(min, max)) {
  53445. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53446. if (distance > currentDistance) {
  53447. distance = currentDistance;
  53448. currentSprite = sprite;
  53449. if (fastCheck) {
  53450. break;
  53451. }
  53452. }
  53453. }
  53454. }
  53455. if (currentSprite) {
  53456. var result = new BABYLON.PickingInfo();
  53457. result.hit = true;
  53458. result.pickedSprite = currentSprite;
  53459. result.distance = distance;
  53460. return result;
  53461. }
  53462. return null;
  53463. };
  53464. SpriteManager.prototype.render = function () {
  53465. // Check
  53466. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53467. return;
  53468. var engine = this._scene.getEngine();
  53469. var baseSize = this._spriteTexture.getBaseSize();
  53470. // Sprites
  53471. var deltaTime = engine.getDeltaTime();
  53472. var max = Math.min(this._capacity, this.sprites.length);
  53473. var rowSize = baseSize.width / this.cellWidth;
  53474. var offset = 0;
  53475. for (var index = 0; index < max; index++) {
  53476. var sprite = this.sprites[index];
  53477. if (!sprite || !sprite.isVisible) {
  53478. continue;
  53479. }
  53480. sprite._animate(deltaTime);
  53481. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53482. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53483. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53484. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53485. }
  53486. this._buffer.update(this._vertexData);
  53487. // Render
  53488. var effect = this._effectBase;
  53489. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53490. effect = this._effectFog;
  53491. }
  53492. engine.enableEffect(effect);
  53493. var viewMatrix = this._scene.getViewMatrix();
  53494. effect.setTexture("diffuseSampler", this._spriteTexture);
  53495. effect.setMatrix("view", viewMatrix);
  53496. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53497. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53498. // Fog
  53499. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53500. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53501. effect.setColor3("vFogColor", this._scene.fogColor);
  53502. }
  53503. // VBOs
  53504. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53505. // Draw order
  53506. engine.setDepthFunctionToLessOrEqual();
  53507. effect.setBool("alphaTest", true);
  53508. engine.setColorWrite(false);
  53509. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53510. engine.setColorWrite(true);
  53511. effect.setBool("alphaTest", false);
  53512. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53513. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53514. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53515. };
  53516. SpriteManager.prototype.dispose = function () {
  53517. if (this._buffer) {
  53518. this._buffer.dispose();
  53519. this._buffer = null;
  53520. }
  53521. if (this._indexBuffer) {
  53522. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53523. this._indexBuffer = null;
  53524. }
  53525. if (this._spriteTexture) {
  53526. this._spriteTexture.dispose();
  53527. this._spriteTexture = null;
  53528. }
  53529. // Remove from scene
  53530. var index = this._scene.spriteManagers.indexOf(this);
  53531. this._scene.spriteManagers.splice(index, 1);
  53532. // Callback
  53533. this.onDisposeObservable.notifyObservers(this);
  53534. this.onDisposeObservable.clear();
  53535. };
  53536. return SpriteManager;
  53537. }());
  53538. BABYLON.SpriteManager = SpriteManager;
  53539. })(BABYLON || (BABYLON = {}));
  53540. //# sourceMappingURL=babylon.spriteManager.js.map
  53541. var BABYLON;
  53542. (function (BABYLON) {
  53543. var Sprite = /** @class */ (function () {
  53544. function Sprite(name, manager) {
  53545. this.name = name;
  53546. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53547. this.width = 1.0;
  53548. this.height = 1.0;
  53549. this.angle = 0;
  53550. this.cellIndex = 0;
  53551. this.invertU = 0;
  53552. this.invertV = 0;
  53553. this.animations = new Array();
  53554. this.isPickable = false;
  53555. this._animationStarted = false;
  53556. this._loopAnimation = false;
  53557. this._fromIndex = 0;
  53558. this._toIndex = 0;
  53559. this._delay = 0;
  53560. this._direction = 1;
  53561. this._time = 0;
  53562. /**
  53563. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53564. */
  53565. this.isVisible = true;
  53566. this._manager = manager;
  53567. this._manager.sprites.push(this);
  53568. this.position = BABYLON.Vector3.Zero();
  53569. }
  53570. Object.defineProperty(Sprite.prototype, "size", {
  53571. get: function () {
  53572. return this.width;
  53573. },
  53574. set: function (value) {
  53575. this.width = value;
  53576. this.height = value;
  53577. },
  53578. enumerable: true,
  53579. configurable: true
  53580. });
  53581. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53582. this._fromIndex = from;
  53583. this._toIndex = to;
  53584. this._loopAnimation = loop;
  53585. this._delay = delay;
  53586. this._animationStarted = true;
  53587. this._direction = from < to ? 1 : -1;
  53588. this.cellIndex = from;
  53589. this._time = 0;
  53590. this._onAnimationEnd = onAnimationEnd;
  53591. };
  53592. Sprite.prototype.stopAnimation = function () {
  53593. this._animationStarted = false;
  53594. };
  53595. Sprite.prototype._animate = function (deltaTime) {
  53596. if (!this._animationStarted)
  53597. return;
  53598. this._time += deltaTime;
  53599. if (this._time > this._delay) {
  53600. this._time = this._time % this._delay;
  53601. this.cellIndex += this._direction;
  53602. if (this.cellIndex > this._toIndex) {
  53603. if (this._loopAnimation) {
  53604. this.cellIndex = this._fromIndex;
  53605. }
  53606. else {
  53607. this.cellIndex = this._toIndex;
  53608. this._animationStarted = false;
  53609. if (this._onAnimationEnd) {
  53610. this._onAnimationEnd();
  53611. }
  53612. if (this.disposeWhenFinishedAnimating) {
  53613. this.dispose();
  53614. }
  53615. }
  53616. }
  53617. }
  53618. };
  53619. Sprite.prototype.dispose = function () {
  53620. for (var i = 0; i < this._manager.sprites.length; i++) {
  53621. if (this._manager.sprites[i] == this) {
  53622. this._manager.sprites.splice(i, 1);
  53623. }
  53624. }
  53625. };
  53626. return Sprite;
  53627. }());
  53628. BABYLON.Sprite = Sprite;
  53629. })(BABYLON || (BABYLON = {}));
  53630. //# sourceMappingURL=babylon.sprite.js.map
  53631. var BABYLON;
  53632. (function (BABYLON) {
  53633. var IntersectionInfo = /** @class */ (function () {
  53634. function IntersectionInfo(bu, bv, distance) {
  53635. this.bu = bu;
  53636. this.bv = bv;
  53637. this.distance = distance;
  53638. this.faceId = 0;
  53639. this.subMeshId = 0;
  53640. }
  53641. return IntersectionInfo;
  53642. }());
  53643. BABYLON.IntersectionInfo = IntersectionInfo;
  53644. /**
  53645. * Information about the result of picking within a scene
  53646. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53647. */
  53648. var PickingInfo = /** @class */ (function () {
  53649. function PickingInfo() {
  53650. /**
  53651. * If the pick collided with an object
  53652. */
  53653. this.hit = false;
  53654. /**
  53655. * Distance away where the pick collided
  53656. */
  53657. this.distance = 0;
  53658. /**
  53659. * The location of pick collision
  53660. */
  53661. this.pickedPoint = null;
  53662. /**
  53663. * The mesh corrisponding the the pick collision
  53664. */
  53665. this.pickedMesh = null;
  53666. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53667. this.bu = 0;
  53668. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53669. this.bv = 0;
  53670. /** The id of the face on the mesh that was picked */
  53671. this.faceId = -1;
  53672. /** Id of the the submesh that was picked */
  53673. this.subMeshId = 0;
  53674. /** If a sprite was picked, this will be the sprite the pick collided with */
  53675. this.pickedSprite = null;
  53676. /**
  53677. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53678. */
  53679. this.originMesh = null;
  53680. /**
  53681. * The ray that was used to perform the picking.
  53682. */
  53683. this.ray = null;
  53684. }
  53685. /**
  53686. * Gets the normal corrispodning to the face the pick collided with
  53687. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53688. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53689. * @returns The normal corrispodning to the face the pick collided with
  53690. */
  53691. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53692. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53693. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53694. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53695. return null;
  53696. }
  53697. var indices = this.pickedMesh.getIndices();
  53698. if (!indices) {
  53699. return null;
  53700. }
  53701. var result;
  53702. if (useVerticesNormals) {
  53703. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53704. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53705. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53706. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53707. normal0 = normal0.scale(this.bu);
  53708. normal1 = normal1.scale(this.bv);
  53709. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53710. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53711. }
  53712. else {
  53713. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53714. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53715. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53716. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53717. var p1p2 = vertex1.subtract(vertex2);
  53718. var p3p2 = vertex3.subtract(vertex2);
  53719. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53720. }
  53721. if (useWorldCoordinates) {
  53722. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53723. }
  53724. return BABYLON.Vector3.Normalize(result);
  53725. };
  53726. /**
  53727. * Gets the texture coordinates of where the pick occured
  53728. * @returns the vector containing the coordnates of the texture
  53729. */
  53730. PickingInfo.prototype.getTextureCoordinates = function () {
  53731. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53732. return null;
  53733. }
  53734. var indices = this.pickedMesh.getIndices();
  53735. if (!indices) {
  53736. return null;
  53737. }
  53738. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53739. if (!uvs) {
  53740. return null;
  53741. }
  53742. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53743. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53744. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53745. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53746. uv1 = uv1.scale(this.bu);
  53747. uv2 = uv2.scale(this.bv);
  53748. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53749. };
  53750. return PickingInfo;
  53751. }());
  53752. BABYLON.PickingInfo = PickingInfo;
  53753. })(BABYLON || (BABYLON = {}));
  53754. //# sourceMappingURL=babylon.pickingInfo.js.map
  53755. var BABYLON;
  53756. (function (BABYLON) {
  53757. var Ray = /** @class */ (function () {
  53758. function Ray(origin, direction, length) {
  53759. if (length === void 0) { length = Number.MAX_VALUE; }
  53760. this.origin = origin;
  53761. this.direction = direction;
  53762. this.length = length;
  53763. }
  53764. // Methods
  53765. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53766. var d = 0.0;
  53767. var maxValue = Number.MAX_VALUE;
  53768. var inv;
  53769. var min;
  53770. var max;
  53771. var temp;
  53772. if (Math.abs(this.direction.x) < 0.0000001) {
  53773. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53774. return false;
  53775. }
  53776. }
  53777. else {
  53778. inv = 1.0 / this.direction.x;
  53779. min = (minimum.x - this.origin.x) * inv;
  53780. max = (maximum.x - this.origin.x) * inv;
  53781. if (max === -Infinity) {
  53782. max = Infinity;
  53783. }
  53784. if (min > max) {
  53785. temp = min;
  53786. min = max;
  53787. max = temp;
  53788. }
  53789. d = Math.max(min, d);
  53790. maxValue = Math.min(max, maxValue);
  53791. if (d > maxValue) {
  53792. return false;
  53793. }
  53794. }
  53795. if (Math.abs(this.direction.y) < 0.0000001) {
  53796. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53797. return false;
  53798. }
  53799. }
  53800. else {
  53801. inv = 1.0 / this.direction.y;
  53802. min = (minimum.y - this.origin.y) * inv;
  53803. max = (maximum.y - this.origin.y) * inv;
  53804. if (max === -Infinity) {
  53805. max = Infinity;
  53806. }
  53807. if (min > max) {
  53808. temp = min;
  53809. min = max;
  53810. max = temp;
  53811. }
  53812. d = Math.max(min, d);
  53813. maxValue = Math.min(max, maxValue);
  53814. if (d > maxValue) {
  53815. return false;
  53816. }
  53817. }
  53818. if (Math.abs(this.direction.z) < 0.0000001) {
  53819. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53820. return false;
  53821. }
  53822. }
  53823. else {
  53824. inv = 1.0 / this.direction.z;
  53825. min = (minimum.z - this.origin.z) * inv;
  53826. max = (maximum.z - this.origin.z) * inv;
  53827. if (max === -Infinity) {
  53828. max = Infinity;
  53829. }
  53830. if (min > max) {
  53831. temp = min;
  53832. min = max;
  53833. max = temp;
  53834. }
  53835. d = Math.max(min, d);
  53836. maxValue = Math.min(max, maxValue);
  53837. if (d > maxValue) {
  53838. return false;
  53839. }
  53840. }
  53841. return true;
  53842. };
  53843. Ray.prototype.intersectsBox = function (box) {
  53844. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53845. };
  53846. Ray.prototype.intersectsSphere = function (sphere) {
  53847. var x = sphere.center.x - this.origin.x;
  53848. var y = sphere.center.y - this.origin.y;
  53849. var z = sphere.center.z - this.origin.z;
  53850. var pyth = (x * x) + (y * y) + (z * z);
  53851. var rr = sphere.radius * sphere.radius;
  53852. if (pyth <= rr) {
  53853. return true;
  53854. }
  53855. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53856. if (dot < 0.0) {
  53857. return false;
  53858. }
  53859. var temp = pyth - (dot * dot);
  53860. return temp <= rr;
  53861. };
  53862. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53863. if (!this._edge1) {
  53864. this._edge1 = BABYLON.Vector3.Zero();
  53865. this._edge2 = BABYLON.Vector3.Zero();
  53866. this._pvec = BABYLON.Vector3.Zero();
  53867. this._tvec = BABYLON.Vector3.Zero();
  53868. this._qvec = BABYLON.Vector3.Zero();
  53869. }
  53870. vertex1.subtractToRef(vertex0, this._edge1);
  53871. vertex2.subtractToRef(vertex0, this._edge2);
  53872. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53873. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53874. if (det === 0) {
  53875. return null;
  53876. }
  53877. var invdet = 1 / det;
  53878. this.origin.subtractToRef(vertex0, this._tvec);
  53879. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53880. if (bu < 0 || bu > 1.0) {
  53881. return null;
  53882. }
  53883. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53884. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53885. if (bv < 0 || bu + bv > 1.0) {
  53886. return null;
  53887. }
  53888. //check if the distance is longer than the predefined length.
  53889. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53890. if (distance > this.length) {
  53891. return null;
  53892. }
  53893. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53894. };
  53895. Ray.prototype.intersectsPlane = function (plane) {
  53896. var distance;
  53897. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53898. if (Math.abs(result1) < 9.99999997475243E-07) {
  53899. return null;
  53900. }
  53901. else {
  53902. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53903. distance = (-plane.d - result2) / result1;
  53904. if (distance < 0.0) {
  53905. if (distance < -9.99999997475243E-07) {
  53906. return null;
  53907. }
  53908. else {
  53909. return 0;
  53910. }
  53911. }
  53912. return distance;
  53913. }
  53914. };
  53915. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53916. var tm = BABYLON.Tmp.Matrix[0];
  53917. mesh.getWorldMatrix().invertToRef(tm);
  53918. if (this._tmpRay) {
  53919. Ray.TransformToRef(this, tm, this._tmpRay);
  53920. }
  53921. else {
  53922. this._tmpRay = Ray.Transform(this, tm);
  53923. }
  53924. return mesh.intersects(this._tmpRay, fastCheck);
  53925. };
  53926. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53927. if (results) {
  53928. results.length = 0;
  53929. }
  53930. else {
  53931. results = [];
  53932. }
  53933. for (var i = 0; i < meshes.length; i++) {
  53934. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53935. if (pickInfo.hit) {
  53936. results.push(pickInfo);
  53937. }
  53938. }
  53939. results.sort(this._comparePickingInfo);
  53940. return results;
  53941. };
  53942. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53943. if (pickingInfoA.distance < pickingInfoB.distance) {
  53944. return -1;
  53945. }
  53946. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53947. return 1;
  53948. }
  53949. else {
  53950. return 0;
  53951. }
  53952. };
  53953. /**
  53954. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53955. * @param sega the first point of the segment to test the intersection against
  53956. * @param segb the second point of the segment to test the intersection against
  53957. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53958. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53959. */
  53960. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53961. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53962. var u = segb.subtract(sega);
  53963. var v = rsegb.subtract(this.origin);
  53964. var w = sega.subtract(this.origin);
  53965. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53966. var b = BABYLON.Vector3.Dot(u, v);
  53967. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53968. var d = BABYLON.Vector3.Dot(u, w);
  53969. var e = BABYLON.Vector3.Dot(v, w);
  53970. var D = a * c - b * b; // always >= 0
  53971. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53972. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53973. // compute the line parameters of the two closest points
  53974. if (D < Ray.smallnum) { // the lines are almost parallel
  53975. sN = 0.0; // force using point P0 on segment S1
  53976. sD = 1.0; // to prevent possible division by 0.0 later
  53977. tN = e;
  53978. tD = c;
  53979. }
  53980. else { // get the closest points on the infinite lines
  53981. sN = (b * e - c * d);
  53982. tN = (a * e - b * d);
  53983. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  53984. sN = 0.0;
  53985. tN = e;
  53986. tD = c;
  53987. }
  53988. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  53989. sN = sD;
  53990. tN = e + b;
  53991. tD = c;
  53992. }
  53993. }
  53994. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  53995. tN = 0.0;
  53996. // recompute sc for this edge
  53997. if (-d < 0.0) {
  53998. sN = 0.0;
  53999. }
  54000. else if (-d > a)
  54001. sN = sD;
  54002. else {
  54003. sN = -d;
  54004. sD = a;
  54005. }
  54006. }
  54007. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54008. tN = tD;
  54009. // recompute sc for this edge
  54010. if ((-d + b) < 0.0) {
  54011. sN = 0;
  54012. }
  54013. else if ((-d + b) > a) {
  54014. sN = sD;
  54015. }
  54016. else {
  54017. sN = (-d + b);
  54018. sD = a;
  54019. }
  54020. }
  54021. // finally do the division to get sc and tc
  54022. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54023. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54024. // get the difference of the two closest points
  54025. var qtc = v.multiplyByFloats(tc, tc, tc);
  54026. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54027. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54028. if (isIntersected) {
  54029. return qtc.length();
  54030. }
  54031. return -1;
  54032. };
  54033. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54034. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54035. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54036. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54037. this.direction.normalize();
  54038. return this;
  54039. };
  54040. // Statics
  54041. Ray.Zero = function () {
  54042. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54043. };
  54044. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54045. var result = Ray.Zero();
  54046. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54047. };
  54048. /**
  54049. * 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
  54050. * transformed to the given world matrix.
  54051. * @param origin The origin point
  54052. * @param end The end point
  54053. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54054. */
  54055. Ray.CreateNewFromTo = function (origin, end, world) {
  54056. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54057. var direction = end.subtract(origin);
  54058. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54059. direction.normalize();
  54060. return Ray.Transform(new Ray(origin, direction, length), world);
  54061. };
  54062. Ray.Transform = function (ray, matrix) {
  54063. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54064. Ray.TransformToRef(ray, matrix, result);
  54065. return result;
  54066. };
  54067. Ray.TransformToRef = function (ray, matrix, result) {
  54068. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54069. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54070. result.length = ray.length;
  54071. var dir = result.direction;
  54072. var len = dir.length();
  54073. if (!(len === 0 || len === 1)) {
  54074. var num = 1.0 / len;
  54075. dir.x *= num;
  54076. dir.y *= num;
  54077. dir.z *= num;
  54078. result.length *= len;
  54079. }
  54080. };
  54081. Ray.smallnum = 0.00000001;
  54082. Ray.rayl = 10e8;
  54083. return Ray;
  54084. }());
  54085. BABYLON.Ray = Ray;
  54086. })(BABYLON || (BABYLON = {}));
  54087. //# sourceMappingURL=babylon.ray.js.map
  54088. var BABYLON;
  54089. (function (BABYLON) {
  54090. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54091. if (boxMin.x > sphereCenter.x + sphereRadius)
  54092. return false;
  54093. if (sphereCenter.x - sphereRadius > boxMax.x)
  54094. return false;
  54095. if (boxMin.y > sphereCenter.y + sphereRadius)
  54096. return false;
  54097. if (sphereCenter.y - sphereRadius > boxMax.y)
  54098. return false;
  54099. if (boxMin.z > sphereCenter.z + sphereRadius)
  54100. return false;
  54101. if (sphereCenter.z - sphereRadius > boxMax.z)
  54102. return false;
  54103. return true;
  54104. };
  54105. var getLowestRoot = (function () {
  54106. var result = { root: 0, found: false };
  54107. return function (a, b, c, maxR) {
  54108. result.root = 0;
  54109. result.found = false;
  54110. var determinant = b * b - 4.0 * a * c;
  54111. if (determinant < 0)
  54112. return result;
  54113. var sqrtD = Math.sqrt(determinant);
  54114. var r1 = (-b - sqrtD) / (2.0 * a);
  54115. var r2 = (-b + sqrtD) / (2.0 * a);
  54116. if (r1 > r2) {
  54117. var temp = r2;
  54118. r2 = r1;
  54119. r1 = temp;
  54120. }
  54121. if (r1 > 0 && r1 < maxR) {
  54122. result.root = r1;
  54123. result.found = true;
  54124. return result;
  54125. }
  54126. if (r2 > 0 && r2 < maxR) {
  54127. result.root = r2;
  54128. result.found = true;
  54129. return result;
  54130. }
  54131. return result;
  54132. };
  54133. })();
  54134. var Collider = /** @class */ (function () {
  54135. function Collider() {
  54136. this._collisionPoint = BABYLON.Vector3.Zero();
  54137. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54138. this._tempVector = BABYLON.Vector3.Zero();
  54139. this._tempVector2 = BABYLON.Vector3.Zero();
  54140. this._tempVector3 = BABYLON.Vector3.Zero();
  54141. this._tempVector4 = BABYLON.Vector3.Zero();
  54142. this._edge = BABYLON.Vector3.Zero();
  54143. this._baseToVertex = BABYLON.Vector3.Zero();
  54144. this._destinationPoint = BABYLON.Vector3.Zero();
  54145. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54146. this._displacementVector = BABYLON.Vector3.Zero();
  54147. this._radius = BABYLON.Vector3.One();
  54148. this._retry = 0;
  54149. this._basePointWorld = BABYLON.Vector3.Zero();
  54150. this._velocityWorld = BABYLON.Vector3.Zero();
  54151. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54152. this._collisionMask = -1;
  54153. }
  54154. Object.defineProperty(Collider.prototype, "collisionMask", {
  54155. get: function () {
  54156. return this._collisionMask;
  54157. },
  54158. set: function (mask) {
  54159. this._collisionMask = !isNaN(mask) ? mask : -1;
  54160. },
  54161. enumerable: true,
  54162. configurable: true
  54163. });
  54164. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54165. /**
  54166. * Gets the plane normal used to compute the sliding response (in local space)
  54167. */
  54168. get: function () {
  54169. return this._slidePlaneNormal;
  54170. },
  54171. enumerable: true,
  54172. configurable: true
  54173. });
  54174. // Methods
  54175. Collider.prototype._initialize = function (source, dir, e) {
  54176. this._velocity = dir;
  54177. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54178. this._basePoint = source;
  54179. source.multiplyToRef(this._radius, this._basePointWorld);
  54180. dir.multiplyToRef(this._radius, this._velocityWorld);
  54181. this._velocityWorldLength = this._velocityWorld.length();
  54182. this._epsilon = e;
  54183. this.collisionFound = false;
  54184. };
  54185. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54186. pa.subtractToRef(point, this._tempVector);
  54187. pb.subtractToRef(point, this._tempVector2);
  54188. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54189. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54190. if (d < 0)
  54191. return false;
  54192. pc.subtractToRef(point, this._tempVector3);
  54193. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54194. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54195. if (d < 0)
  54196. return false;
  54197. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54198. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54199. return d >= 0;
  54200. };
  54201. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54202. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54203. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54204. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54205. return false;
  54206. }
  54207. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54208. return false;
  54209. return true;
  54210. };
  54211. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54212. var t0;
  54213. var embeddedInPlane = false;
  54214. //defensive programming, actually not needed.
  54215. if (!trianglePlaneArray) {
  54216. trianglePlaneArray = [];
  54217. }
  54218. if (!trianglePlaneArray[faceIndex]) {
  54219. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54220. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54221. }
  54222. var trianglePlane = trianglePlaneArray[faceIndex];
  54223. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54224. return;
  54225. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54226. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54227. if (normalDotVelocity == 0) {
  54228. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54229. return;
  54230. embeddedInPlane = true;
  54231. t0 = 0;
  54232. }
  54233. else {
  54234. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54235. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54236. if (t0 > t1) {
  54237. var temp = t1;
  54238. t1 = t0;
  54239. t0 = temp;
  54240. }
  54241. if (t0 > 1.0 || t1 < 0.0)
  54242. return;
  54243. if (t0 < 0)
  54244. t0 = 0;
  54245. if (t0 > 1.0)
  54246. t0 = 1.0;
  54247. }
  54248. this._collisionPoint.copyFromFloats(0, 0, 0);
  54249. var found = false;
  54250. var t = 1.0;
  54251. if (!embeddedInPlane) {
  54252. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54253. this._velocity.scaleToRef(t0, this._tempVector);
  54254. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54255. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54256. found = true;
  54257. t = t0;
  54258. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54259. }
  54260. }
  54261. if (!found) {
  54262. var velocitySquaredLength = this._velocity.lengthSquared();
  54263. var a = velocitySquaredLength;
  54264. this._basePoint.subtractToRef(p1, this._tempVector);
  54265. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54266. var c = this._tempVector.lengthSquared() - 1.0;
  54267. var lowestRoot = getLowestRoot(a, b, c, t);
  54268. if (lowestRoot.found) {
  54269. t = lowestRoot.root;
  54270. found = true;
  54271. this._collisionPoint.copyFrom(p1);
  54272. }
  54273. this._basePoint.subtractToRef(p2, this._tempVector);
  54274. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54275. c = this._tempVector.lengthSquared() - 1.0;
  54276. lowestRoot = getLowestRoot(a, b, c, t);
  54277. if (lowestRoot.found) {
  54278. t = lowestRoot.root;
  54279. found = true;
  54280. this._collisionPoint.copyFrom(p2);
  54281. }
  54282. this._basePoint.subtractToRef(p3, this._tempVector);
  54283. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54284. c = this._tempVector.lengthSquared() - 1.0;
  54285. lowestRoot = getLowestRoot(a, b, c, t);
  54286. if (lowestRoot.found) {
  54287. t = lowestRoot.root;
  54288. found = true;
  54289. this._collisionPoint.copyFrom(p3);
  54290. }
  54291. p2.subtractToRef(p1, this._edge);
  54292. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54293. var edgeSquaredLength = this._edge.lengthSquared();
  54294. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54295. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54296. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54297. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54298. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54299. lowestRoot = getLowestRoot(a, b, c, t);
  54300. if (lowestRoot.found) {
  54301. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54302. if (f >= 0.0 && f <= 1.0) {
  54303. t = lowestRoot.root;
  54304. found = true;
  54305. this._edge.scaleInPlace(f);
  54306. p1.addToRef(this._edge, this._collisionPoint);
  54307. }
  54308. }
  54309. p3.subtractToRef(p2, this._edge);
  54310. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54311. edgeSquaredLength = this._edge.lengthSquared();
  54312. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54313. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54314. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54315. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54316. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54317. lowestRoot = getLowestRoot(a, b, c, t);
  54318. if (lowestRoot.found) {
  54319. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54320. if (f >= 0.0 && f <= 1.0) {
  54321. t = lowestRoot.root;
  54322. found = true;
  54323. this._edge.scaleInPlace(f);
  54324. p2.addToRef(this._edge, this._collisionPoint);
  54325. }
  54326. }
  54327. p1.subtractToRef(p3, this._edge);
  54328. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54329. edgeSquaredLength = this._edge.lengthSquared();
  54330. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54331. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54332. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54333. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54334. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54335. lowestRoot = getLowestRoot(a, b, c, t);
  54336. if (lowestRoot.found) {
  54337. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54338. if (f >= 0.0 && f <= 1.0) {
  54339. t = lowestRoot.root;
  54340. found = true;
  54341. this._edge.scaleInPlace(f);
  54342. p3.addToRef(this._edge, this._collisionPoint);
  54343. }
  54344. }
  54345. }
  54346. if (found) {
  54347. var distToCollision = t * this._velocity.length();
  54348. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54349. if (!this.intersectionPoint) {
  54350. this.intersectionPoint = this._collisionPoint.clone();
  54351. }
  54352. else {
  54353. this.intersectionPoint.copyFrom(this._collisionPoint);
  54354. }
  54355. this._nearestDistance = distToCollision;
  54356. this.collisionFound = true;
  54357. }
  54358. }
  54359. };
  54360. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54361. for (var i = indexStart; i < indexEnd; i += 3) {
  54362. var p1 = pts[indices[i] - decal];
  54363. var p2 = pts[indices[i + 1] - decal];
  54364. var p3 = pts[indices[i + 2] - decal];
  54365. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54366. }
  54367. };
  54368. Collider.prototype._getResponse = function (pos, vel) {
  54369. pos.addToRef(vel, this._destinationPoint);
  54370. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54371. this._basePoint.addToRef(vel, pos);
  54372. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54373. this._slidePlaneNormal.normalize();
  54374. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54375. pos.addInPlace(this._displacementVector);
  54376. this.intersectionPoint.addInPlace(this._displacementVector);
  54377. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54378. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54379. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54380. };
  54381. return Collider;
  54382. }());
  54383. BABYLON.Collider = Collider;
  54384. })(BABYLON || (BABYLON = {}));
  54385. //# sourceMappingURL=babylon.collider.js.map
  54386. var BABYLON;
  54387. (function (BABYLON) {
  54388. //WebWorker code will be inserted to this variable.
  54389. BABYLON.CollisionWorker = "";
  54390. /** Defines supported task for worker process */
  54391. var WorkerTaskType;
  54392. (function (WorkerTaskType) {
  54393. /** Initialization */
  54394. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54395. /** Update of geometry */
  54396. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54397. /** Evaluate collision */
  54398. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54399. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54400. /** Defines kind of replies returned by worker */
  54401. var WorkerReplyType;
  54402. (function (WorkerReplyType) {
  54403. /** Success */
  54404. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54405. /** Unkown error */
  54406. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54407. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54408. var CollisionCoordinatorWorker = /** @class */ (function () {
  54409. function CollisionCoordinatorWorker() {
  54410. var _this = this;
  54411. this._scaledPosition = BABYLON.Vector3.Zero();
  54412. this._scaledVelocity = BABYLON.Vector3.Zero();
  54413. this.onMeshUpdated = function (transformNode) {
  54414. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54415. };
  54416. this.onGeometryUpdated = function (geometry) {
  54417. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54418. };
  54419. this._afterRender = function () {
  54420. if (!_this._init)
  54421. return;
  54422. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54423. return;
  54424. }
  54425. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54426. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54427. if (_this._runningUpdated > 4) {
  54428. return;
  54429. }
  54430. ++_this._runningUpdated;
  54431. var payload = {
  54432. updatedMeshes: _this._addUpdateMeshesList,
  54433. updatedGeometries: _this._addUpdateGeometriesList,
  54434. removedGeometries: _this._toRemoveGeometryArray,
  54435. removedMeshes: _this._toRemoveMeshesArray
  54436. };
  54437. var message = {
  54438. payload: payload,
  54439. taskType: WorkerTaskType.UPDATE
  54440. };
  54441. var serializable = [];
  54442. for (var id in payload.updatedGeometries) {
  54443. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54444. //prepare transferables
  54445. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54446. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54447. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54448. }
  54449. }
  54450. _this._worker.postMessage(message, serializable);
  54451. _this._addUpdateMeshesList = {};
  54452. _this._addUpdateGeometriesList = {};
  54453. _this._toRemoveGeometryArray = [];
  54454. _this._toRemoveMeshesArray = [];
  54455. };
  54456. this._onMessageFromWorker = function (e) {
  54457. var returnData = e.data;
  54458. if (returnData.error != WorkerReplyType.SUCCESS) {
  54459. //TODO what errors can be returned from the worker?
  54460. BABYLON.Tools.Warn("error returned from worker!");
  54461. return;
  54462. }
  54463. switch (returnData.taskType) {
  54464. case WorkerTaskType.INIT:
  54465. _this._init = true;
  54466. //Update the worked with ALL of the scene's current state
  54467. _this._scene.meshes.forEach(function (mesh) {
  54468. _this.onMeshAdded(mesh);
  54469. });
  54470. _this._scene.getGeometries().forEach(function (geometry) {
  54471. _this.onGeometryAdded(geometry);
  54472. });
  54473. break;
  54474. case WorkerTaskType.UPDATE:
  54475. _this._runningUpdated--;
  54476. break;
  54477. case WorkerTaskType.COLLIDE:
  54478. var returnPayload = returnData.payload;
  54479. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54480. return;
  54481. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54482. if (callback) {
  54483. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54484. if (mesh) {
  54485. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54486. }
  54487. }
  54488. //cleanup
  54489. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54490. break;
  54491. }
  54492. };
  54493. this._collisionsCallbackArray = [];
  54494. this._init = false;
  54495. this._runningUpdated = 0;
  54496. this._addUpdateMeshesList = {};
  54497. this._addUpdateGeometriesList = {};
  54498. this._toRemoveGeometryArray = [];
  54499. this._toRemoveMeshesArray = [];
  54500. }
  54501. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54502. if (!this._init)
  54503. return;
  54504. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54505. return;
  54506. position.divideToRef(collider._radius, this._scaledPosition);
  54507. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54508. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54509. var payload = {
  54510. collider: {
  54511. position: this._scaledPosition.asArray(),
  54512. velocity: this._scaledVelocity.asArray(),
  54513. radius: collider._radius.asArray()
  54514. },
  54515. collisionId: collisionIndex,
  54516. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54517. maximumRetry: maximumRetry
  54518. };
  54519. var message = {
  54520. payload: payload,
  54521. taskType: WorkerTaskType.COLLIDE
  54522. };
  54523. this._worker.postMessage(message);
  54524. };
  54525. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54526. this._scene = scene;
  54527. this._scene.registerAfterRender(this._afterRender);
  54528. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54529. this._worker = new Worker(workerUrl);
  54530. this._worker.onmessage = this._onMessageFromWorker;
  54531. var message = {
  54532. payload: {},
  54533. taskType: WorkerTaskType.INIT
  54534. };
  54535. this._worker.postMessage(message);
  54536. };
  54537. CollisionCoordinatorWorker.prototype.destroy = function () {
  54538. this._scene.unregisterAfterRender(this._afterRender);
  54539. this._worker.terminate();
  54540. };
  54541. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54542. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54543. this.onMeshUpdated(mesh);
  54544. };
  54545. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54546. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54547. };
  54548. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54549. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54550. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54551. this.onGeometryUpdated(geometry);
  54552. };
  54553. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54554. this._toRemoveGeometryArray.push(geometry.id);
  54555. };
  54556. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54557. var submeshes = [];
  54558. if (mesh.subMeshes) {
  54559. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54560. var boundingInfo = sm.getBoundingInfo();
  54561. return {
  54562. position: idx,
  54563. verticesStart: sm.verticesStart,
  54564. verticesCount: sm.verticesCount,
  54565. indexStart: sm.indexStart,
  54566. indexCount: sm.indexCount,
  54567. hasMaterial: !!sm.getMaterial(),
  54568. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54569. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54570. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54571. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54572. };
  54573. });
  54574. }
  54575. var geometryId = null;
  54576. if (mesh instanceof BABYLON.Mesh) {
  54577. var geometry = mesh.geometry;
  54578. geometryId = geometry ? geometry.id : null;
  54579. }
  54580. else if (mesh instanceof BABYLON.InstancedMesh) {
  54581. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54582. geometryId = geometry ? geometry.id : null;
  54583. }
  54584. var boundingInfo = mesh.getBoundingInfo();
  54585. return {
  54586. uniqueId: mesh.uniqueId,
  54587. id: mesh.id,
  54588. name: mesh.name,
  54589. geometryId: geometryId,
  54590. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54591. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54592. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54593. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54594. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54595. subMeshes: submeshes,
  54596. checkCollisions: mesh.checkCollisions
  54597. };
  54598. };
  54599. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54600. return {
  54601. id: geometry.id,
  54602. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54603. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54604. indices: new Uint32Array(geometry.getIndices() || []),
  54605. };
  54606. };
  54607. return CollisionCoordinatorWorker;
  54608. }());
  54609. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54610. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54611. function CollisionCoordinatorLegacy() {
  54612. this._scaledPosition = BABYLON.Vector3.Zero();
  54613. this._scaledVelocity = BABYLON.Vector3.Zero();
  54614. this._finalPosition = BABYLON.Vector3.Zero();
  54615. }
  54616. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54617. position.divideToRef(collider._radius, this._scaledPosition);
  54618. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54619. collider.collidedMesh = null;
  54620. collider._retry = 0;
  54621. collider._initialVelocity = this._scaledVelocity;
  54622. collider._initialPosition = this._scaledPosition;
  54623. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54624. this._finalPosition.multiplyInPlace(collider._radius);
  54625. //run the callback
  54626. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54627. };
  54628. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54629. this._scene = scene;
  54630. };
  54631. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54632. //Legacy need no destruction method.
  54633. };
  54634. //No update in legacy mode
  54635. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54636. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54637. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54638. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54639. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54640. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54641. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54642. if (excludedMesh === void 0) { excludedMesh = null; }
  54643. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54644. if (collider._retry >= maximumRetry) {
  54645. finalPosition.copyFrom(position);
  54646. return;
  54647. }
  54648. // Check if this is a mesh else camera or -1
  54649. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54650. collider._initialize(position, velocity, closeDistance);
  54651. // Check all meshes
  54652. for (var index = 0; index < this._scene.meshes.length; index++) {
  54653. var mesh = this._scene.meshes[index];
  54654. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54655. mesh._checkCollision(collider);
  54656. }
  54657. }
  54658. if (!collider.collisionFound) {
  54659. position.addToRef(velocity, finalPosition);
  54660. return;
  54661. }
  54662. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54663. collider._getResponse(position, velocity);
  54664. }
  54665. if (velocity.length() <= closeDistance) {
  54666. finalPosition.copyFrom(position);
  54667. return;
  54668. }
  54669. collider._retry++;
  54670. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54671. };
  54672. return CollisionCoordinatorLegacy;
  54673. }());
  54674. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54675. })(BABYLON || (BABYLON = {}));
  54676. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54677. var BABYLON;
  54678. (function (BABYLON) {
  54679. /**
  54680. * A particle represents one of the element emitted by a particle system.
  54681. * This is mainly define by its coordinates, direction, velocity and age.
  54682. */
  54683. var Particle = /** @class */ (function () {
  54684. /**
  54685. * Creates a new instance Particle
  54686. * @param particleSystem the particle system the particle belongs to
  54687. */
  54688. function Particle(
  54689. /**
  54690. * particleSystem the particle system the particle belongs to.
  54691. */
  54692. particleSystem) {
  54693. this.particleSystem = particleSystem;
  54694. /**
  54695. * The world position of the particle in the scene.
  54696. */
  54697. this.position = BABYLON.Vector3.Zero();
  54698. /**
  54699. * The world direction of the particle in the scene.
  54700. */
  54701. this.direction = BABYLON.Vector3.Zero();
  54702. /**
  54703. * The color of the particle.
  54704. */
  54705. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54706. /**
  54707. * The color change of the particle per step.
  54708. */
  54709. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54710. /**
  54711. * Defines how long will the life of the particle be.
  54712. */
  54713. this.lifeTime = 1.0;
  54714. /**
  54715. * The current age of the particle.
  54716. */
  54717. this.age = 0;
  54718. /**
  54719. * The current size of the particle.
  54720. */
  54721. this.size = 0;
  54722. /**
  54723. * The current scale of the particle.
  54724. */
  54725. this.scale = new BABYLON.Vector2(1, 1);
  54726. /**
  54727. * The current angle of the particle.
  54728. */
  54729. this.angle = 0;
  54730. /**
  54731. * Defines how fast is the angle changing.
  54732. */
  54733. this.angularSpeed = 0;
  54734. /**
  54735. * Defines the cell index used by the particle to be rendered from a sprite.
  54736. */
  54737. this.cellIndex = 0;
  54738. this._currentFrameCounter = 0;
  54739. if (!this.particleSystem.isAnimationSheetEnabled) {
  54740. return;
  54741. }
  54742. this.updateCellInfoFromSystem();
  54743. }
  54744. Particle.prototype.updateCellInfoFromSystem = function () {
  54745. this.cellIndex = this.particleSystem.startSpriteCellID;
  54746. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54747. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54748. }
  54749. else {
  54750. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54751. }
  54752. };
  54753. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54754. // (ageOffset / scaledUpdateSpeed) / available cells
  54755. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54756. this._currentFrameCounter += scaledUpdateSpeed;
  54757. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54758. this._currentFrameCounter = 0;
  54759. this.cellIndex++;
  54760. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54761. this.cellIndex = this.particleSystem.endSpriteCellID;
  54762. }
  54763. }
  54764. };
  54765. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54766. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54767. this.cellIndex++;
  54768. this._currentFrameCounter = 0;
  54769. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54770. if (this.particleSystem.spriteCellLoop) {
  54771. this.cellIndex = this.particleSystem.startSpriteCellID;
  54772. }
  54773. else {
  54774. this.cellIndex = this.particleSystem.endSpriteCellID;
  54775. }
  54776. }
  54777. }
  54778. else {
  54779. this._currentFrameCounter++;
  54780. }
  54781. };
  54782. /**
  54783. * Copy the properties of particle to another one.
  54784. * @param other the particle to copy the information to.
  54785. */
  54786. Particle.prototype.copyTo = function (other) {
  54787. other.position.copyFrom(this.position);
  54788. other.direction.copyFrom(this.direction);
  54789. other.color.copyFrom(this.color);
  54790. other.colorStep.copyFrom(this.colorStep);
  54791. other.lifeTime = this.lifeTime;
  54792. other.age = this.age;
  54793. other.size = this.size;
  54794. other.scale.copyFrom(this.scale);
  54795. other.angle = this.angle;
  54796. other.angularSpeed = this.angularSpeed;
  54797. other.particleSystem = this.particleSystem;
  54798. other.cellIndex = this.cellIndex;
  54799. };
  54800. return Particle;
  54801. }());
  54802. BABYLON.Particle = Particle;
  54803. })(BABYLON || (BABYLON = {}));
  54804. //# sourceMappingURL=babylon.particle.js.map
  54805. var BABYLON;
  54806. (function (BABYLON) {
  54807. /**
  54808. * This represents a particle system in Babylon.
  54809. * 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.
  54810. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54811. * @example https://doc.babylonjs.com/babylon101/particles
  54812. */
  54813. var ParticleSystem = /** @class */ (function () {
  54814. /**
  54815. * Instantiates a particle system.
  54816. * 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.
  54817. * @param name The name of the particle system
  54818. * @param capacity The max number of particles alive at the same time
  54819. * @param scene The scene the particle system belongs to
  54820. * @param customEffect a custom effect used to change the way particles are rendered by default
  54821. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54822. * @param epsilon Offset used to render the particles
  54823. */
  54824. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54825. if (customEffect === void 0) { customEffect = null; }
  54826. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54827. if (epsilon === void 0) { epsilon = 0.01; }
  54828. var _this = this;
  54829. /**
  54830. * List of animations used by the particle system.
  54831. */
  54832. this.animations = [];
  54833. /**
  54834. * The rendering group used by the Particle system to chose when to render.
  54835. */
  54836. this.renderingGroupId = 0;
  54837. /**
  54838. * The emitter represents the Mesh or position we are attaching the particle system to.
  54839. */
  54840. this.emitter = null;
  54841. /**
  54842. * The maximum number of particles to emit per frame
  54843. */
  54844. this.emitRate = 10;
  54845. /**
  54846. * If you want to launch only a few particles at once, that can be done, as well.
  54847. */
  54848. this.manualEmitCount = -1;
  54849. /**
  54850. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54851. */
  54852. this.updateSpeed = 0.01;
  54853. /**
  54854. * The amount of time the particle system is running (depends of the overall update speed).
  54855. */
  54856. this.targetStopDuration = 0;
  54857. /**
  54858. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54859. */
  54860. this.disposeOnStop = false;
  54861. /**
  54862. * Minimum power of emitting particles.
  54863. */
  54864. this.minEmitPower = 1;
  54865. /**
  54866. * Maximum power of emitting particles.
  54867. */
  54868. this.maxEmitPower = 1;
  54869. /**
  54870. * Minimum life time of emitting particles.
  54871. */
  54872. this.minLifeTime = 1;
  54873. /**
  54874. * Maximum life time of emitting particles.
  54875. */
  54876. this.maxLifeTime = 1;
  54877. /**
  54878. * Minimum Size of emitting particles.
  54879. */
  54880. this.minSize = 1;
  54881. /**
  54882. * Maximum Size of emitting particles.
  54883. */
  54884. this.maxSize = 1;
  54885. /**
  54886. * Minimum scale of emitting particles on X axis.
  54887. */
  54888. this.minScaleX = 1;
  54889. /**
  54890. * Maximum scale of emitting particles on X axis.
  54891. */
  54892. this.maxScaleX = 1;
  54893. /**
  54894. * Minimum scale of emitting particles on Y axis.
  54895. */
  54896. this.minScaleY = 1;
  54897. /**
  54898. * Maximum scale of emitting particles on Y axis.
  54899. */
  54900. this.maxScaleY = 1;
  54901. /**
  54902. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54903. */
  54904. this.minAngularSpeed = 0;
  54905. /**
  54906. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54907. */
  54908. this.maxAngularSpeed = 0;
  54909. /**
  54910. * The layer mask we are rendering the particles through.
  54911. */
  54912. this.layerMask = 0x0FFFFFFF;
  54913. /**
  54914. * This can help using your own shader to render the particle system.
  54915. * The according effect will be created
  54916. */
  54917. this.customShader = null;
  54918. /**
  54919. * By default particle system starts as soon as they are created. This prevents the
  54920. * automatic start to happen and let you decide when to start emitting particles.
  54921. */
  54922. this.preventAutoStart = false;
  54923. /**
  54924. * Callback triggered when the particle animation is ending.
  54925. */
  54926. this.onAnimationEnd = null;
  54927. /**
  54928. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54929. */
  54930. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54931. /**
  54932. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54933. * to override the particles.
  54934. */
  54935. this.forceDepthWrite = false;
  54936. /**
  54937. * You can use gravity if you want to give an orientation to your particles.
  54938. */
  54939. this.gravity = BABYLON.Vector3.Zero();
  54940. /**
  54941. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54942. */
  54943. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54944. /**
  54945. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54946. */
  54947. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54948. /**
  54949. * Color the particle will have at the end of its lifetime.
  54950. */
  54951. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54952. /**
  54953. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  54954. */
  54955. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54956. /**
  54957. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  54958. */
  54959. this.spriteCellLoop = true;
  54960. /**
  54961. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  54962. */
  54963. this.spriteCellChangeSpeed = 0;
  54964. /**
  54965. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  54966. */
  54967. this.startSpriteCellID = 0;
  54968. /**
  54969. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  54970. */
  54971. this.endSpriteCellID = 0;
  54972. /**
  54973. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  54974. */
  54975. this.spriteCellWidth = 0;
  54976. /**
  54977. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  54978. */
  54979. this.spriteCellHeight = 0;
  54980. /**
  54981. * An event triggered when the system is disposed.
  54982. */
  54983. this.onDisposeObservable = new BABYLON.Observable();
  54984. this._particles = new Array();
  54985. this._stockParticles = new Array();
  54986. this._newPartsExcess = 0;
  54987. this._vertexBuffers = {};
  54988. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54989. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54990. this._scaledDirection = BABYLON.Vector3.Zero();
  54991. this._scaledGravity = BABYLON.Vector3.Zero();
  54992. this._currentRenderId = -1;
  54993. this._started = false;
  54994. this._stopped = false;
  54995. this._actualFrame = 0;
  54996. this._vertexBufferSize = 12;
  54997. // start of sub system methods
  54998. /**
  54999. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55000. * Its lifetime will start back at 0.
  55001. */
  55002. this.recycleParticle = function (particle) {
  55003. var lastParticle = _this._particles.pop();
  55004. if (lastParticle !== particle) {
  55005. lastParticle.copyTo(particle);
  55006. }
  55007. _this._stockParticles.push(lastParticle);
  55008. };
  55009. this._createParticle = function () {
  55010. var particle;
  55011. if (_this._stockParticles.length !== 0) {
  55012. particle = _this._stockParticles.pop();
  55013. particle.age = 0;
  55014. particle.cellIndex = _this.startSpriteCellID;
  55015. }
  55016. else {
  55017. particle = new BABYLON.Particle(_this);
  55018. }
  55019. return particle;
  55020. };
  55021. this._emitFromParticle = function (particle) {
  55022. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55023. return;
  55024. }
  55025. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55026. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55027. subSystem._rootParticleSystem = _this;
  55028. _this.activeSubSystems.push(subSystem);
  55029. subSystem.start();
  55030. };
  55031. this._appendParticleVertexes = null;
  55032. this.id = name;
  55033. this.name = name;
  55034. this._capacity = capacity;
  55035. this._epsilon = epsilon;
  55036. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55037. if (isAnimationSheetEnabled) {
  55038. this._vertexBufferSize = 13;
  55039. }
  55040. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55041. this._customEffect = customEffect;
  55042. scene.particleSystems.push(this);
  55043. this._createIndexBuffer();
  55044. // 13 floats per particle (x, y, z, r, g, b, a, angle, scaleX, scaleY, offsetX, offsetY) + 1 filler
  55045. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55046. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55047. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55048. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55049. var options = this._vertexBuffer.createVertexBuffer("options", 7, 3);
  55050. var size = this._vertexBuffer.createVertexBuffer("size", 10, 2);
  55051. if (this._isAnimationSheetEnabled) {
  55052. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 12, 1);
  55053. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55054. }
  55055. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55056. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55057. this._vertexBuffers["options"] = options;
  55058. this._vertexBuffers["size"] = size;
  55059. // Default emitter type
  55060. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55061. this.updateFunction = function (particles) {
  55062. for (var index = 0; index < particles.length; index++) {
  55063. var particle = particles[index];
  55064. particle.age += _this._scaledUpdateSpeed;
  55065. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55066. _this._emitFromParticle(particle);
  55067. _this.recycleParticle(particle);
  55068. index--;
  55069. continue;
  55070. }
  55071. else {
  55072. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55073. particle.color.addInPlace(_this._scaledColorStep);
  55074. if (particle.color.a < 0)
  55075. particle.color.a = 0;
  55076. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55077. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55078. particle.position.addInPlace(_this._scaledDirection);
  55079. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55080. particle.direction.addInPlace(_this._scaledGravity);
  55081. if (_this._isAnimationSheetEnabled) {
  55082. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55083. }
  55084. }
  55085. }
  55086. };
  55087. }
  55088. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55089. /**
  55090. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55091. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55092. */
  55093. get: function () {
  55094. if (this.particleEmitterType.direction1) {
  55095. return this.particleEmitterType.direction1;
  55096. }
  55097. return BABYLON.Vector3.Zero();
  55098. },
  55099. set: function (value) {
  55100. if (this.particleEmitterType.direction1) {
  55101. this.particleEmitterType.direction1 = value;
  55102. }
  55103. },
  55104. enumerable: true,
  55105. configurable: true
  55106. });
  55107. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55108. /**
  55109. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55110. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55111. */
  55112. get: function () {
  55113. if (this.particleEmitterType.direction2) {
  55114. return this.particleEmitterType.direction2;
  55115. }
  55116. return BABYLON.Vector3.Zero();
  55117. },
  55118. set: function (value) {
  55119. if (this.particleEmitterType.direction2) {
  55120. this.particleEmitterType.direction2 = value;
  55121. }
  55122. },
  55123. enumerable: true,
  55124. configurable: true
  55125. });
  55126. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55127. /**
  55128. * 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.
  55129. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55130. */
  55131. get: function () {
  55132. if (this.particleEmitterType.minEmitBox) {
  55133. return this.particleEmitterType.minEmitBox;
  55134. }
  55135. return BABYLON.Vector3.Zero();
  55136. },
  55137. set: function (value) {
  55138. if (this.particleEmitterType.minEmitBox) {
  55139. this.particleEmitterType.minEmitBox = value;
  55140. }
  55141. },
  55142. enumerable: true,
  55143. configurable: true
  55144. });
  55145. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55146. /**
  55147. * 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.
  55148. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55149. */
  55150. get: function () {
  55151. if (this.particleEmitterType.maxEmitBox) {
  55152. return this.particleEmitterType.maxEmitBox;
  55153. }
  55154. return BABYLON.Vector3.Zero();
  55155. },
  55156. set: function (value) {
  55157. if (this.particleEmitterType.maxEmitBox) {
  55158. this.particleEmitterType.maxEmitBox = value;
  55159. }
  55160. },
  55161. enumerable: true,
  55162. configurable: true
  55163. });
  55164. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55165. /**
  55166. * Sets a callback that will be triggered when the system is disposed.
  55167. */
  55168. set: function (callback) {
  55169. if (this._onDisposeObserver) {
  55170. this.onDisposeObservable.remove(this._onDisposeObserver);
  55171. }
  55172. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55173. },
  55174. enumerable: true,
  55175. configurable: true
  55176. });
  55177. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55178. /**
  55179. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55180. */
  55181. get: function () {
  55182. return this._isAnimationSheetEnabled;
  55183. },
  55184. enumerable: true,
  55185. configurable: true
  55186. });
  55187. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55188. //end of Sub-emitter
  55189. /**
  55190. * Gets the current list of active particles
  55191. */
  55192. get: function () {
  55193. return this._particles;
  55194. },
  55195. enumerable: true,
  55196. configurable: true
  55197. });
  55198. /**
  55199. * Returns the string "ParticleSystem"
  55200. * @returns a string containing the class name
  55201. */
  55202. ParticleSystem.prototype.getClassName = function () {
  55203. return "ParticleSystem";
  55204. };
  55205. ParticleSystem.prototype._createIndexBuffer = function () {
  55206. var indices = [];
  55207. var index = 0;
  55208. for (var count = 0; count < this._capacity; count++) {
  55209. indices.push(index);
  55210. indices.push(index + 1);
  55211. indices.push(index + 2);
  55212. indices.push(index);
  55213. indices.push(index + 2);
  55214. indices.push(index + 3);
  55215. index += 4;
  55216. }
  55217. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55218. };
  55219. /**
  55220. * Gets the maximum number of particles active at the same time.
  55221. * @returns The max number of active particles.
  55222. */
  55223. ParticleSystem.prototype.getCapacity = function () {
  55224. return this._capacity;
  55225. };
  55226. /**
  55227. * Gets Wether there are still active particles in the system.
  55228. * @returns True if it is alive, otherwise false.
  55229. */
  55230. ParticleSystem.prototype.isAlive = function () {
  55231. return this._alive;
  55232. };
  55233. /**
  55234. * Gets Wether the system has been started.
  55235. * @returns True if it has been started, otherwise false.
  55236. */
  55237. ParticleSystem.prototype.isStarted = function () {
  55238. return this._started;
  55239. };
  55240. /**
  55241. * Starts the particle system and begins to emit.
  55242. */
  55243. ParticleSystem.prototype.start = function () {
  55244. this._started = true;
  55245. this._stopped = false;
  55246. this._actualFrame = 0;
  55247. if (this.subEmitters && this.subEmitters.length != 0) {
  55248. this.activeSubSystems = new Array();
  55249. }
  55250. };
  55251. /**
  55252. * Stops the particle system.
  55253. * @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.
  55254. */
  55255. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55256. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55257. this._stopped = true;
  55258. if (stopSubEmitters) {
  55259. this._stopSubEmitters();
  55260. }
  55261. };
  55262. // animation sheet
  55263. /**
  55264. * Remove all active particles
  55265. */
  55266. ParticleSystem.prototype.reset = function () {
  55267. this._stockParticles = [];
  55268. this._particles = [];
  55269. };
  55270. /**
  55271. * @hidden (for internal use only)
  55272. */
  55273. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55274. var offset = index * this._vertexBufferSize;
  55275. this._vertexData[offset] = particle.position.x;
  55276. this._vertexData[offset + 1] = particle.position.y;
  55277. this._vertexData[offset + 2] = particle.position.z;
  55278. this._vertexData[offset + 3] = particle.color.r;
  55279. this._vertexData[offset + 4] = particle.color.g;
  55280. this._vertexData[offset + 5] = particle.color.b;
  55281. this._vertexData[offset + 6] = particle.color.a;
  55282. this._vertexData[offset + 7] = particle.angle;
  55283. this._vertexData[offset + 8] = offsetX;
  55284. this._vertexData[offset + 9] = offsetY;
  55285. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  55286. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  55287. };
  55288. /**
  55289. * @hidden (for internal use only)
  55290. */
  55291. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55292. if (offsetX === 0)
  55293. offsetX = this._epsilon;
  55294. else if (offsetX === 1)
  55295. offsetX = 1 - this._epsilon;
  55296. if (offsetY === 0)
  55297. offsetY = this._epsilon;
  55298. else if (offsetY === 1)
  55299. offsetY = 1 - this._epsilon;
  55300. var offset = index * this._vertexBufferSize;
  55301. this._vertexData[offset] = particle.position.x;
  55302. this._vertexData[offset + 1] = particle.position.y;
  55303. this._vertexData[offset + 2] = particle.position.z;
  55304. this._vertexData[offset + 3] = particle.color.r;
  55305. this._vertexData[offset + 4] = particle.color.g;
  55306. this._vertexData[offset + 5] = particle.color.b;
  55307. this._vertexData[offset + 6] = particle.color.a;
  55308. this._vertexData[offset + 7] = particle.angle;
  55309. this._vertexData[offset + 8] = offsetX;
  55310. this._vertexData[offset + 9] = offsetY;
  55311. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  55312. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  55313. this._vertexData[offset + 12] = particle.cellIndex;
  55314. };
  55315. ParticleSystem.prototype._stopSubEmitters = function () {
  55316. if (!this.activeSubSystems) {
  55317. return;
  55318. }
  55319. this.activeSubSystems.forEach(function (subSystem) {
  55320. subSystem.stop(true);
  55321. });
  55322. this.activeSubSystems = new Array();
  55323. };
  55324. ParticleSystem.prototype._removeFromRoot = function () {
  55325. if (!this._rootParticleSystem) {
  55326. return;
  55327. }
  55328. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55329. if (index !== -1) {
  55330. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55331. }
  55332. };
  55333. // end of sub system methods
  55334. ParticleSystem.prototype._update = function (newParticles) {
  55335. // Update current
  55336. this._alive = this._particles.length > 0;
  55337. this.updateFunction(this._particles);
  55338. // Add new ones
  55339. var worldMatrix;
  55340. if (this.emitter.position) {
  55341. var emitterMesh = this.emitter;
  55342. worldMatrix = emitterMesh.getWorldMatrix();
  55343. }
  55344. else {
  55345. var emitterPosition = this.emitter;
  55346. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55347. }
  55348. var particle;
  55349. for (var index = 0; index < newParticles; index++) {
  55350. if (this._particles.length === this._capacity) {
  55351. break;
  55352. }
  55353. particle = this._createParticle();
  55354. this._particles.push(particle);
  55355. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55356. if (this.startPositionFunction) {
  55357. this.startPositionFunction(worldMatrix, particle.position, particle);
  55358. }
  55359. else {
  55360. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55361. }
  55362. if (this.startDirectionFunction) {
  55363. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55364. }
  55365. else {
  55366. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55367. }
  55368. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55369. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55370. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55371. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55372. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55373. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55374. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55375. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55376. }
  55377. };
  55378. ParticleSystem.prototype._getEffect = function () {
  55379. if (this._customEffect) {
  55380. return this._customEffect;
  55381. }
  55382. ;
  55383. var defines = [];
  55384. if (this._scene.clipPlane) {
  55385. defines.push("#define CLIPPLANE");
  55386. }
  55387. if (this._isAnimationSheetEnabled) {
  55388. defines.push("#define ANIMATESHEET");
  55389. }
  55390. // Effect
  55391. var join = defines.join("\n");
  55392. if (this._cachedDefines !== join) {
  55393. this._cachedDefines = join;
  55394. var attributesNamesOrOptions;
  55395. var effectCreationOption;
  55396. if (this._isAnimationSheetEnabled) {
  55397. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size", "cellIndex"];
  55398. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55399. }
  55400. else {
  55401. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size",];
  55402. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55403. }
  55404. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55405. }
  55406. return this._effect;
  55407. };
  55408. /**
  55409. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55410. */
  55411. ParticleSystem.prototype.animate = function () {
  55412. if (!this._started)
  55413. return;
  55414. var effect = this._getEffect();
  55415. // Check
  55416. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55417. return;
  55418. if (this._currentRenderId === this._scene.getRenderId()) {
  55419. return;
  55420. }
  55421. this._currentRenderId = this._scene.getRenderId();
  55422. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55423. // determine the number of particles we need to create
  55424. var newParticles;
  55425. if (this.manualEmitCount > -1) {
  55426. newParticles = this.manualEmitCount;
  55427. this._newPartsExcess = 0;
  55428. this.manualEmitCount = 0;
  55429. }
  55430. else {
  55431. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55432. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55433. }
  55434. if (this._newPartsExcess > 1.0) {
  55435. newParticles += this._newPartsExcess >> 0;
  55436. this._newPartsExcess -= this._newPartsExcess >> 0;
  55437. }
  55438. this._alive = false;
  55439. if (!this._stopped) {
  55440. this._actualFrame += this._scaledUpdateSpeed;
  55441. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55442. this.stop();
  55443. }
  55444. else {
  55445. newParticles = 0;
  55446. }
  55447. this._update(newParticles);
  55448. // Stopped?
  55449. if (this._stopped) {
  55450. if (!this._alive) {
  55451. this._started = false;
  55452. if (this.onAnimationEnd) {
  55453. this.onAnimationEnd();
  55454. }
  55455. if (this.disposeOnStop) {
  55456. this._scene._toBeDisposed.push(this);
  55457. }
  55458. }
  55459. }
  55460. // Animation sheet
  55461. if (this._isAnimationSheetEnabled) {
  55462. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55463. }
  55464. else {
  55465. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55466. }
  55467. // Update VBO
  55468. var offset = 0;
  55469. for (var index = 0; index < this._particles.length; index++) {
  55470. var particle = this._particles[index];
  55471. this._appendParticleVertexes(offset, particle);
  55472. offset += 4;
  55473. }
  55474. if (this._vertexBuffer) {
  55475. this._vertexBuffer.update(this._vertexData);
  55476. }
  55477. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55478. this.stop();
  55479. }
  55480. };
  55481. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55482. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55483. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55484. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55485. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55486. };
  55487. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55488. this._appendParticleVertex(offset++, particle, 0, 0);
  55489. this._appendParticleVertex(offset++, particle, 1, 0);
  55490. this._appendParticleVertex(offset++, particle, 1, 1);
  55491. this._appendParticleVertex(offset++, particle, 0, 1);
  55492. };
  55493. /**
  55494. * Rebuilds the particle system.
  55495. */
  55496. ParticleSystem.prototype.rebuild = function () {
  55497. this._createIndexBuffer();
  55498. if (this._vertexBuffer) {
  55499. this._vertexBuffer._rebuild();
  55500. }
  55501. };
  55502. /**
  55503. * Is this system ready to be used/rendered
  55504. * @return true if the system is ready
  55505. */
  55506. ParticleSystem.prototype.isReady = function () {
  55507. var effect = this._getEffect();
  55508. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55509. return false;
  55510. }
  55511. return true;
  55512. };
  55513. /**
  55514. * Renders the particle system in its current state.
  55515. * @returns the current number of particles
  55516. */
  55517. ParticleSystem.prototype.render = function () {
  55518. var effect = this._getEffect();
  55519. // Check
  55520. if (!this.isReady() || !this._particles.length) {
  55521. return 0;
  55522. }
  55523. var engine = this._scene.getEngine();
  55524. // Render
  55525. engine.enableEffect(effect);
  55526. engine.setState(false);
  55527. var viewMatrix = this._scene.getViewMatrix();
  55528. effect.setTexture("diffuseSampler", this.particleTexture);
  55529. effect.setMatrix("view", viewMatrix);
  55530. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55531. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55532. var baseSize = this.particleTexture.getBaseSize();
  55533. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55534. }
  55535. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55536. if (this._scene.clipPlane) {
  55537. var clipPlane = this._scene.clipPlane;
  55538. var invView = viewMatrix.clone();
  55539. invView.invert();
  55540. effect.setMatrix("invView", invView);
  55541. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55542. }
  55543. // VBOs
  55544. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55545. // Draw order
  55546. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55547. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55548. }
  55549. else {
  55550. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55551. }
  55552. if (this.forceDepthWrite) {
  55553. engine.setDepthWrite(true);
  55554. }
  55555. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55556. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55557. return this._particles.length;
  55558. };
  55559. /**
  55560. * Disposes the particle system and free the associated resources
  55561. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55562. */
  55563. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55564. if (disposeTexture === void 0) { disposeTexture = true; }
  55565. if (this._vertexBuffer) {
  55566. this._vertexBuffer.dispose();
  55567. this._vertexBuffer = null;
  55568. }
  55569. if (this._indexBuffer) {
  55570. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55571. this._indexBuffer = null;
  55572. }
  55573. if (disposeTexture && this.particleTexture) {
  55574. this.particleTexture.dispose();
  55575. this.particleTexture = null;
  55576. }
  55577. this._removeFromRoot();
  55578. // Remove from scene
  55579. var index = this._scene.particleSystems.indexOf(this);
  55580. if (index > -1) {
  55581. this._scene.particleSystems.splice(index, 1);
  55582. }
  55583. // Callback
  55584. this.onDisposeObservable.notifyObservers(this);
  55585. this.onDisposeObservable.clear();
  55586. };
  55587. /**
  55588. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55589. * @param radius The radius of the sphere to emit from
  55590. * @returns the emitter
  55591. */
  55592. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55593. if (radius === void 0) { radius = 1; }
  55594. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55595. this.particleEmitterType = particleEmitter;
  55596. return particleEmitter;
  55597. };
  55598. /**
  55599. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55600. * @param radius The radius of the sphere to emit from
  55601. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55602. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55603. * @returns the emitter
  55604. */
  55605. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55606. if (radius === void 0) { radius = 1; }
  55607. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55608. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55609. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55610. this.particleEmitterType = particleEmitter;
  55611. return particleEmitter;
  55612. };
  55613. /**
  55614. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55615. * @param radius The radius of the cone to emit from
  55616. * @param angle The base angle of the cone
  55617. * @returns the emitter
  55618. */
  55619. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55620. if (radius === void 0) { radius = 1; }
  55621. if (angle === void 0) { angle = Math.PI / 4; }
  55622. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55623. this.particleEmitterType = particleEmitter;
  55624. return particleEmitter;
  55625. };
  55626. // 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.
  55627. /**
  55628. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55629. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55630. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55631. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55632. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55633. * @returns the emitter
  55634. */
  55635. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55636. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55637. this.particleEmitterType = particleEmitter;
  55638. this.direction1 = direction1;
  55639. this.direction2 = direction2;
  55640. this.minEmitBox = minEmitBox;
  55641. this.maxEmitBox = maxEmitBox;
  55642. return particleEmitter;
  55643. };
  55644. // Clone
  55645. /**
  55646. * Clones the particle system.
  55647. * @param name The name of the cloned object
  55648. * @param newEmitter The new emitter to use
  55649. * @returns the cloned particle system
  55650. */
  55651. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55652. var custom = null;
  55653. var program = null;
  55654. if (this.customShader != null) {
  55655. program = this.customShader;
  55656. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55657. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55658. }
  55659. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55660. result.customShader = program;
  55661. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55662. if (newEmitter === undefined) {
  55663. newEmitter = this.emitter;
  55664. }
  55665. result.emitter = newEmitter;
  55666. if (this.particleTexture) {
  55667. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55668. }
  55669. if (!this.preventAutoStart) {
  55670. result.start();
  55671. }
  55672. return result;
  55673. };
  55674. /**
  55675. * Serializes the particle system to a JSON object.
  55676. * @returns the JSON object
  55677. */
  55678. ParticleSystem.prototype.serialize = function () {
  55679. var serializationObject = {};
  55680. serializationObject.name = this.name;
  55681. serializationObject.id = this.id;
  55682. // Emitter
  55683. if (this.emitter.position) {
  55684. var emitterMesh = this.emitter;
  55685. serializationObject.emitterId = emitterMesh.id;
  55686. }
  55687. else {
  55688. var emitterPosition = this.emitter;
  55689. serializationObject.emitter = emitterPosition.asArray();
  55690. }
  55691. serializationObject.capacity = this.getCapacity();
  55692. if (this.particleTexture) {
  55693. serializationObject.textureName = this.particleTexture.name;
  55694. }
  55695. // Animations
  55696. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55697. // Particle system
  55698. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55699. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55700. serializationObject.minSize = this.minSize;
  55701. serializationObject.maxSize = this.maxSize;
  55702. serializationObject.minScaleX = this.minScaleX;
  55703. serializationObject.maxScaleX = this.maxScaleX;
  55704. serializationObject.minScaleY = this.minScaleY;
  55705. serializationObject.maxScaleY = this.maxScaleY;
  55706. serializationObject.minEmitPower = this.minEmitPower;
  55707. serializationObject.maxEmitPower = this.maxEmitPower;
  55708. serializationObject.minLifeTime = this.minLifeTime;
  55709. serializationObject.maxLifeTime = this.maxLifeTime;
  55710. serializationObject.emitRate = this.emitRate;
  55711. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55712. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55713. serializationObject.gravity = this.gravity.asArray();
  55714. serializationObject.direction1 = this.direction1.asArray();
  55715. serializationObject.direction2 = this.direction2.asArray();
  55716. serializationObject.color1 = this.color1.asArray();
  55717. serializationObject.color2 = this.color2.asArray();
  55718. serializationObject.colorDead = this.colorDead.asArray();
  55719. serializationObject.updateSpeed = this.updateSpeed;
  55720. serializationObject.targetStopDuration = this.targetStopDuration;
  55721. serializationObject.textureMask = this.textureMask.asArray();
  55722. serializationObject.blendMode = this.blendMode;
  55723. serializationObject.customShader = this.customShader;
  55724. serializationObject.preventAutoStart = this.preventAutoStart;
  55725. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55726. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55727. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55728. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55729. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55730. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55731. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55732. // Emitter
  55733. if (this.particleEmitterType) {
  55734. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55735. }
  55736. return serializationObject;
  55737. };
  55738. /**
  55739. * Parses a JSON object to create a particle system.
  55740. * @param parsedParticleSystem The JSON object to parse
  55741. * @param scene The scene to create the particle system in
  55742. * @param rootUrl The root url to use to load external dependencies like texture
  55743. * @returns the Parsed particle system
  55744. */
  55745. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55746. var name = parsedParticleSystem.name;
  55747. var custom = null;
  55748. var program = null;
  55749. if (parsedParticleSystem.customShader) {
  55750. program = parsedParticleSystem.customShader;
  55751. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55752. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55753. }
  55754. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55755. particleSystem.customShader = program;
  55756. if (parsedParticleSystem.id) {
  55757. particleSystem.id = parsedParticleSystem.id;
  55758. }
  55759. // Auto start
  55760. if (parsedParticleSystem.preventAutoStart) {
  55761. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55762. }
  55763. // Texture
  55764. if (parsedParticleSystem.textureName) {
  55765. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55766. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55767. }
  55768. // Emitter
  55769. if (parsedParticleSystem.emitterId) {
  55770. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55771. }
  55772. else {
  55773. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55774. }
  55775. // Animations
  55776. if (parsedParticleSystem.animations) {
  55777. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55778. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55779. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55780. }
  55781. }
  55782. if (parsedParticleSystem.autoAnimate) {
  55783. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55784. }
  55785. // Particle system
  55786. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55787. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55788. particleSystem.minSize = parsedParticleSystem.minSize;
  55789. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55790. if (parsedParticleSystem.minScaleX) {
  55791. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  55792. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  55793. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  55794. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  55795. }
  55796. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55797. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55798. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55799. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55800. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55801. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  55802. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  55803. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55804. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  55805. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  55806. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55807. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55808. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55809. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55810. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55811. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  55812. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55813. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  55814. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  55815. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  55816. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  55817. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  55818. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  55819. if (!particleSystem.preventAutoStart) {
  55820. particleSystem.start();
  55821. }
  55822. return particleSystem;
  55823. };
  55824. /**
  55825. * Source color is added to the destination color without alpha affecting the result.
  55826. */
  55827. ParticleSystem.BLENDMODE_ONEONE = 0;
  55828. /**
  55829. * Blend current color and particle color using particle’s alpha.
  55830. */
  55831. ParticleSystem.BLENDMODE_STANDARD = 1;
  55832. return ParticleSystem;
  55833. }());
  55834. BABYLON.ParticleSystem = ParticleSystem;
  55835. })(BABYLON || (BABYLON = {}));
  55836. //# sourceMappingURL=babylon.particleSystem.js.map
  55837. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  55838. var BABYLON;
  55839. (function (BABYLON) {
  55840. /**
  55841. * Particle emitter emitting particles from the inside of a box.
  55842. * It emits the particles randomly between 2 given directions.
  55843. */
  55844. var BoxParticleEmitter = /** @class */ (function () {
  55845. /**
  55846. * Creates a new instance BoxParticleEmitter
  55847. */
  55848. function BoxParticleEmitter() {
  55849. /**
  55850. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55851. */
  55852. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  55853. /**
  55854. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55855. */
  55856. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  55857. /**
  55858. * 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.
  55859. */
  55860. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  55861. /**
  55862. * 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.
  55863. */
  55864. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  55865. }
  55866. /**
  55867. * Called by the particle System when the direction is computed for the created particle.
  55868. * @param emitPower is the power of the particle (speed)
  55869. * @param worldMatrix is the world matrix of the particle system
  55870. * @param directionToUpdate is the direction vector to update with the result
  55871. * @param particle is the particle we are computed the direction for
  55872. */
  55873. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55874. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55875. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55876. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55877. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55878. };
  55879. /**
  55880. * Called by the particle System when the position is computed for the created particle.
  55881. * @param worldMatrix is the world matrix of the particle system
  55882. * @param positionToUpdate is the position vector to update with the result
  55883. * @param particle is the particle we are computed the position for
  55884. */
  55885. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55886. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  55887. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  55888. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  55889. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55890. };
  55891. /**
  55892. * Clones the current emitter and returns a copy of it
  55893. * @returns the new emitter
  55894. */
  55895. BoxParticleEmitter.prototype.clone = function () {
  55896. var newOne = new BoxParticleEmitter();
  55897. BABYLON.Tools.DeepCopy(this, newOne);
  55898. return newOne;
  55899. };
  55900. /**
  55901. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55902. * @param effect defines the update shader
  55903. */
  55904. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  55905. effect.setVector3("direction1", this.direction1);
  55906. effect.setVector3("direction2", this.direction2);
  55907. effect.setVector3("minEmitBox", this.minEmitBox);
  55908. effect.setVector3("maxEmitBox", this.maxEmitBox);
  55909. };
  55910. /**
  55911. * Returns a string to use to update the GPU particles update shader
  55912. * @returns a string containng the defines string
  55913. */
  55914. BoxParticleEmitter.prototype.getEffectDefines = function () {
  55915. return "#define BOXEMITTER";
  55916. };
  55917. /**
  55918. * Returns the string "BoxEmitter"
  55919. * @returns a string containing the class name
  55920. */
  55921. BoxParticleEmitter.prototype.getClassName = function () {
  55922. return "BoxEmitter";
  55923. };
  55924. /**
  55925. * Serializes the particle system to a JSON object.
  55926. * @returns the JSON object
  55927. */
  55928. BoxParticleEmitter.prototype.serialize = function () {
  55929. var serializationObject = {};
  55930. serializationObject.type = this.getClassName();
  55931. serializationObject.direction1 = this.direction1.asArray();
  55932. serializationObject.direction2 = this.direction2.asArray();
  55933. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55934. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55935. return serializationObject;
  55936. };
  55937. /**
  55938. * Parse properties from a JSON object
  55939. * @param serializationObject defines the JSON object
  55940. */
  55941. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  55942. this.direction1.copyFrom(serializationObject.direction1);
  55943. this.direction2.copyFrom(serializationObject.direction2);
  55944. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  55945. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  55946. };
  55947. return BoxParticleEmitter;
  55948. }());
  55949. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  55950. })(BABYLON || (BABYLON = {}));
  55951. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  55952. var BABYLON;
  55953. (function (BABYLON) {
  55954. /**
  55955. * Particle emitter emitting particles from the inside of a cone.
  55956. * It emits the particles alongside the cone volume from the base to the particle.
  55957. * The emission direction might be randomized.
  55958. */
  55959. var ConeParticleEmitter = /** @class */ (function () {
  55960. /**
  55961. * Creates a new instance ConeParticleEmitter
  55962. * @param radius the radius of the emission cone (1 by default)
  55963. * @param angles the cone base angle (PI by default)
  55964. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  55965. */
  55966. function ConeParticleEmitter(radius, angle,
  55967. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  55968. directionRandomizer) {
  55969. if (radius === void 0) { radius = 1; }
  55970. if (angle === void 0) { angle = Math.PI; }
  55971. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55972. this.directionRandomizer = directionRandomizer;
  55973. this.angle = angle;
  55974. this.radius = radius;
  55975. }
  55976. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  55977. /**
  55978. * Gets or sets the radius of the emission cone
  55979. */
  55980. get: function () {
  55981. return this._radius;
  55982. },
  55983. set: function (value) {
  55984. this._radius = value;
  55985. this._buildHeight();
  55986. },
  55987. enumerable: true,
  55988. configurable: true
  55989. });
  55990. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  55991. /**
  55992. * Gets or sets the angle of the emission cone
  55993. */
  55994. get: function () {
  55995. return this._angle;
  55996. },
  55997. set: function (value) {
  55998. this._angle = value;
  55999. this._buildHeight();
  56000. },
  56001. enumerable: true,
  56002. configurable: true
  56003. });
  56004. ConeParticleEmitter.prototype._buildHeight = function () {
  56005. if (this._angle !== 0) {
  56006. this._height = this._radius / Math.tan(this._angle / 2);
  56007. }
  56008. else {
  56009. this._height = 1;
  56010. }
  56011. };
  56012. /**
  56013. * Called by the particle System when the direction is computed for the created particle.
  56014. * @param emitPower is the power of the particle (speed)
  56015. * @param worldMatrix is the world matrix of the particle system
  56016. * @param directionToUpdate is the direction vector to update with the result
  56017. * @param particle is the particle we are computed the direction for
  56018. */
  56019. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56020. if (this._angle === 0) {
  56021. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56022. }
  56023. else {
  56024. // measure the direction Vector from the emitter to the particle.
  56025. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56026. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56027. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56028. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56029. direction.x += randX;
  56030. direction.y += randY;
  56031. direction.z += randZ;
  56032. direction.normalize();
  56033. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56034. }
  56035. };
  56036. /**
  56037. * Called by the particle System when the position is computed for the created particle.
  56038. * @param worldMatrix is the world matrix of the particle system
  56039. * @param positionToUpdate is the position vector to update with the result
  56040. * @param particle is the particle we are computed the position for
  56041. */
  56042. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56043. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56044. var h = BABYLON.Scalar.RandomRange(0, 1);
  56045. // Better distribution in a cone at normal angles.
  56046. h = 1 - h * h;
  56047. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56048. radius = radius * h;
  56049. var randX = radius * Math.sin(s);
  56050. var randZ = radius * Math.cos(s);
  56051. var randY = h * this._height;
  56052. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56053. };
  56054. /**
  56055. * Clones the current emitter and returns a copy of it
  56056. * @returns the new emitter
  56057. */
  56058. ConeParticleEmitter.prototype.clone = function () {
  56059. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56060. BABYLON.Tools.DeepCopy(this, newOne);
  56061. return newOne;
  56062. };
  56063. /**
  56064. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56065. * @param effect defines the update shader
  56066. */
  56067. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56068. effect.setFloat("radius", this._radius);
  56069. effect.setFloat("coneAngle", this._angle);
  56070. effect.setFloat("height", this._height);
  56071. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56072. };
  56073. /**
  56074. * Returns a string to use to update the GPU particles update shader
  56075. * @returns a string containng the defines string
  56076. */
  56077. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56078. return "#define CONEEMITTER";
  56079. };
  56080. /**
  56081. * Returns the string "BoxEmitter"
  56082. * @returns a string containing the class name
  56083. */
  56084. ConeParticleEmitter.prototype.getClassName = function () {
  56085. return "ConeEmitter";
  56086. };
  56087. /**
  56088. * Serializes the particle system to a JSON object.
  56089. * @returns the JSON object
  56090. */
  56091. ConeParticleEmitter.prototype.serialize = function () {
  56092. var serializationObject = {};
  56093. serializationObject.type = this.getClassName();
  56094. serializationObject.radius = this._radius;
  56095. serializationObject.angle = this._angle;
  56096. serializationObject.directionRandomizer = this.directionRandomizer;
  56097. return serializationObject;
  56098. };
  56099. /**
  56100. * Parse properties from a JSON object
  56101. * @param serializationObject defines the JSON object
  56102. */
  56103. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56104. this.radius = serializationObject.radius;
  56105. this.angle = serializationObject.angle;
  56106. this.directionRandomizer = serializationObject.directionRandomizer;
  56107. };
  56108. return ConeParticleEmitter;
  56109. }());
  56110. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56111. })(BABYLON || (BABYLON = {}));
  56112. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56113. var BABYLON;
  56114. (function (BABYLON) {
  56115. /**
  56116. * Particle emitter emitting particles from the inside of a sphere.
  56117. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56118. */
  56119. var SphereParticleEmitter = /** @class */ (function () {
  56120. /**
  56121. * Creates a new instance SphereParticleEmitter
  56122. * @param radius the radius of the emission sphere (1 by default)
  56123. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56124. */
  56125. function SphereParticleEmitter(
  56126. /**
  56127. * The radius of the emission sphere.
  56128. */
  56129. radius,
  56130. /**
  56131. * How much to randomize the particle direction [0-1].
  56132. */
  56133. directionRandomizer) {
  56134. if (radius === void 0) { radius = 1; }
  56135. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56136. this.radius = radius;
  56137. this.directionRandomizer = directionRandomizer;
  56138. }
  56139. /**
  56140. * Called by the particle System when the direction is computed for the created particle.
  56141. * @param emitPower is the power of the particle (speed)
  56142. * @param worldMatrix is the world matrix of the particle system
  56143. * @param directionToUpdate is the direction vector to update with the result
  56144. * @param particle is the particle we are computed the direction for
  56145. */
  56146. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56147. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56148. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56149. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56150. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56151. direction.x += randX;
  56152. direction.y += randY;
  56153. direction.z += randZ;
  56154. direction.normalize();
  56155. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56156. };
  56157. /**
  56158. * Called by the particle System when the position is computed for the created particle.
  56159. * @param worldMatrix is the world matrix of the particle system
  56160. * @param positionToUpdate is the position vector to update with the result
  56161. * @param particle is the particle we are computed the position for
  56162. */
  56163. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56164. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56165. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56166. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56167. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56168. var randY = randRadius * Math.cos(theta);
  56169. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56170. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56171. };
  56172. /**
  56173. * Clones the current emitter and returns a copy of it
  56174. * @returns the new emitter
  56175. */
  56176. SphereParticleEmitter.prototype.clone = function () {
  56177. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56178. BABYLON.Tools.DeepCopy(this, newOne);
  56179. return newOne;
  56180. };
  56181. /**
  56182. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56183. * @param effect defines the update shader
  56184. */
  56185. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56186. effect.setFloat("radius", this.radius);
  56187. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56188. };
  56189. /**
  56190. * Returns a string to use to update the GPU particles update shader
  56191. * @returns a string containng the defines string
  56192. */
  56193. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56194. return "#define SPHEREEMITTER";
  56195. };
  56196. /**
  56197. * Returns the string "SphereParticleEmitter"
  56198. * @returns a string containing the class name
  56199. */
  56200. SphereParticleEmitter.prototype.getClassName = function () {
  56201. return "SphereParticleEmitter";
  56202. };
  56203. /**
  56204. * Serializes the particle system to a JSON object.
  56205. * @returns the JSON object
  56206. */
  56207. SphereParticleEmitter.prototype.serialize = function () {
  56208. var serializationObject = {};
  56209. serializationObject.type = this.getClassName();
  56210. serializationObject.radius = this.radius;
  56211. serializationObject.directionRandomizer = this.directionRandomizer;
  56212. return serializationObject;
  56213. };
  56214. /**
  56215. * Parse properties from a JSON object
  56216. * @param serializationObject defines the JSON object
  56217. */
  56218. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56219. this.radius = serializationObject.radius;
  56220. this.directionRandomizer = serializationObject.directionRandomizer;
  56221. };
  56222. return SphereParticleEmitter;
  56223. }());
  56224. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56225. /**
  56226. * Particle emitter emitting particles from the inside of a sphere.
  56227. * It emits the particles randomly between two vectors.
  56228. */
  56229. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56230. __extends(SphereDirectedParticleEmitter, _super);
  56231. /**
  56232. * Creates a new instance SphereDirectedParticleEmitter
  56233. * @param radius the radius of the emission sphere (1 by default)
  56234. * @param direction1 the min limit of the emission direction (up vector by default)
  56235. * @param direction2 the max limit of the emission direction (up vector by default)
  56236. */
  56237. function SphereDirectedParticleEmitter(radius,
  56238. /**
  56239. * The min limit of the emission direction.
  56240. */
  56241. direction1,
  56242. /**
  56243. * The max limit of the emission direction.
  56244. */
  56245. direction2) {
  56246. if (radius === void 0) { radius = 1; }
  56247. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56248. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56249. var _this = _super.call(this, radius) || this;
  56250. _this.direction1 = direction1;
  56251. _this.direction2 = direction2;
  56252. return _this;
  56253. }
  56254. /**
  56255. * Called by the particle System when the direction is computed for the created particle.
  56256. * @param emitPower is the power of the particle (speed)
  56257. * @param worldMatrix is the world matrix of the particle system
  56258. * @param directionToUpdate is the direction vector to update with the result
  56259. * @param particle is the particle we are computed the direction for
  56260. */
  56261. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56262. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56263. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56264. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56265. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56266. };
  56267. /**
  56268. * Clones the current emitter and returns a copy of it
  56269. * @returns the new emitter
  56270. */
  56271. SphereDirectedParticleEmitter.prototype.clone = function () {
  56272. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56273. BABYLON.Tools.DeepCopy(this, newOne);
  56274. return newOne;
  56275. };
  56276. /**
  56277. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56278. * @param effect defines the update shader
  56279. */
  56280. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56281. effect.setFloat("radius", this.radius);
  56282. effect.setVector3("direction1", this.direction1);
  56283. effect.setVector3("direction2", this.direction2);
  56284. };
  56285. /**
  56286. * Returns a string to use to update the GPU particles update shader
  56287. * @returns a string containng the defines string
  56288. */
  56289. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56290. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56291. };
  56292. /**
  56293. * Returns the string "SphereDirectedParticleEmitter"
  56294. * @returns a string containing the class name
  56295. */
  56296. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56297. return "SphereDirectedParticleEmitter";
  56298. };
  56299. /**
  56300. * Serializes the particle system to a JSON object.
  56301. * @returns the JSON object
  56302. */
  56303. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56304. var serializationObject = _super.prototype.serialize.call(this);
  56305. serializationObject.direction1 = this.direction1.asArray();
  56306. serializationObject.direction2 = this.direction2.asArray();
  56307. return serializationObject;
  56308. };
  56309. /**
  56310. * Parse properties from a JSON object
  56311. * @param serializationObject defines the JSON object
  56312. */
  56313. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56314. _super.prototype.parse.call(this, serializationObject);
  56315. this.direction1.copyFrom(serializationObject.direction1);
  56316. this.direction2.copyFrom(serializationObject.direction2);
  56317. };
  56318. return SphereDirectedParticleEmitter;
  56319. }(SphereParticleEmitter));
  56320. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56321. })(BABYLON || (BABYLON = {}));
  56322. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56323. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56324. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56325. s = arguments[i];
  56326. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56327. t[p] = s[p];
  56328. }
  56329. return t;
  56330. };
  56331. var BABYLON;
  56332. (function (BABYLON) {
  56333. /**
  56334. * This represents a GPU particle system in Babylon
  56335. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56336. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56337. */
  56338. var GPUParticleSystem = /** @class */ (function () {
  56339. /**
  56340. * Instantiates a GPU particle system.
  56341. * 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.
  56342. * @param name The name of the particle system
  56343. * @param capacity The max number of particles alive at the same time
  56344. * @param scene The scene the particle system belongs to
  56345. */
  56346. function GPUParticleSystem(name, options, scene) {
  56347. /**
  56348. * The emitter represents the Mesh or position we are attaching the particle system to.
  56349. */
  56350. this.emitter = null;
  56351. /**
  56352. * The rendering group used by the Particle system to chose when to render.
  56353. */
  56354. this.renderingGroupId = 0;
  56355. /**
  56356. * The layer mask we are rendering the particles through.
  56357. */
  56358. this.layerMask = 0x0FFFFFFF;
  56359. this._targetIndex = 0;
  56360. this._currentRenderId = -1;
  56361. this._started = false;
  56362. this._stopped = false;
  56363. this._timeDelta = 0;
  56364. this._attributesStrideSize = 18;
  56365. this._actualFrame = 0;
  56366. /**
  56367. * List of animations used by the particle system.
  56368. */
  56369. this.animations = [];
  56370. /**
  56371. * An event triggered when the system is disposed.
  56372. */
  56373. this.onDisposeObservable = new BABYLON.Observable();
  56374. /**
  56375. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56376. */
  56377. this.updateSpeed = 0.01;
  56378. /**
  56379. * The amount of time the particle system is running (depends of the overall update speed).
  56380. */
  56381. this.targetStopDuration = 0;
  56382. /**
  56383. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56384. */
  56385. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56386. /**
  56387. * Minimum life time of emitting particles.
  56388. */
  56389. this.minLifeTime = 1;
  56390. /**
  56391. * Maximum life time of emitting particles.
  56392. */
  56393. this.maxLifeTime = 1;
  56394. /**
  56395. * Minimum Size of emitting particles.
  56396. */
  56397. this.minSize = 1;
  56398. /**
  56399. * Maximum Size of emitting particles.
  56400. */
  56401. this.maxSize = 1;
  56402. /**
  56403. * Minimum scale of emitting particles on X axis.
  56404. */
  56405. this.minScaleX = 1;
  56406. /**
  56407. * Maximum scale of emitting particles on X axis.
  56408. */
  56409. this.maxScaleX = 1;
  56410. /**
  56411. * Minimum scale of emitting particles on Y axis.
  56412. */
  56413. this.minScaleY = 1;
  56414. /**
  56415. * Maximum scale of emitting particles on Y axis.
  56416. */
  56417. this.maxScaleY = 1;
  56418. /**
  56419. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56420. */
  56421. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56422. /**
  56423. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56424. */
  56425. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56426. /**
  56427. * Color the particle will have at the end of its lifetime.
  56428. */
  56429. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56430. /**
  56431. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56432. */
  56433. this.emitRate = 100;
  56434. /**
  56435. * You can use gravity if you want to give an orientation to your particles.
  56436. */
  56437. this.gravity = BABYLON.Vector3.Zero();
  56438. /**
  56439. * Minimum power of emitting particles.
  56440. */
  56441. this.minEmitPower = 1;
  56442. /**
  56443. * Maximum power of emitting particles.
  56444. */
  56445. this.maxEmitPower = 1;
  56446. /**
  56447. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56448. */
  56449. this.minAngularSpeed = 0;
  56450. /**
  56451. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56452. */
  56453. this.maxAngularSpeed = 0;
  56454. /**
  56455. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56456. * to override the particles.
  56457. */
  56458. this.forceDepthWrite = false;
  56459. this.id = name;
  56460. this.name = name;
  56461. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56462. this._engine = this._scene.getEngine();
  56463. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56464. this._capacity = fullOptions.capacity;
  56465. this._activeCount = fullOptions.capacity;
  56466. this._currentActiveCount = 0;
  56467. this._scene.particleSystems.push(this);
  56468. this._updateEffectOptions = {
  56469. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  56470. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56471. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56472. "angleRange"],
  56473. uniformBuffersNames: [],
  56474. samplers: ["randomSampler"],
  56475. defines: "",
  56476. fallbacks: null,
  56477. onCompiled: null,
  56478. onError: null,
  56479. indexParameters: null,
  56480. maxSimultaneousLights: 0,
  56481. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  56482. };
  56483. // Random data
  56484. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56485. var d = [];
  56486. for (var i = 0; i < maxTextureSize; ++i) {
  56487. d.push(Math.random());
  56488. d.push(Math.random());
  56489. d.push(Math.random());
  56490. d.push(Math.random());
  56491. }
  56492. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56493. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56494. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56495. this._randomTextureSize = maxTextureSize;
  56496. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56497. }
  56498. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56499. /**
  56500. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56501. */
  56502. get: function () {
  56503. if (!BABYLON.Engine.LastCreatedEngine) {
  56504. return false;
  56505. }
  56506. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56507. },
  56508. enumerable: true,
  56509. configurable: true
  56510. });
  56511. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56512. /**
  56513. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56514. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56515. */
  56516. get: function () {
  56517. if (this.particleEmitterType.direction1) {
  56518. return this.particleEmitterType.direction1;
  56519. }
  56520. return BABYLON.Vector3.Zero();
  56521. },
  56522. set: function (value) {
  56523. if (this.particleEmitterType.direction1) {
  56524. this.particleEmitterType.direction1 = value;
  56525. }
  56526. },
  56527. enumerable: true,
  56528. configurable: true
  56529. });
  56530. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56531. /**
  56532. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56533. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56534. */
  56535. get: function () {
  56536. if (this.particleEmitterType.direction2) {
  56537. return this.particleEmitterType.direction2;
  56538. }
  56539. return BABYLON.Vector3.Zero();
  56540. },
  56541. set: function (value) {
  56542. if (this.particleEmitterType.direction2) {
  56543. this.particleEmitterType.direction2 = value;
  56544. }
  56545. },
  56546. enumerable: true,
  56547. configurable: true
  56548. });
  56549. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56550. /**
  56551. * 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.
  56552. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56553. */
  56554. get: function () {
  56555. if (this.particleEmitterType.minEmitBox) {
  56556. return this.particleEmitterType.minEmitBox;
  56557. }
  56558. return BABYLON.Vector3.Zero();
  56559. },
  56560. set: function (value) {
  56561. if (this.particleEmitterType.minEmitBox) {
  56562. this.particleEmitterType.minEmitBox = value;
  56563. }
  56564. },
  56565. enumerable: true,
  56566. configurable: true
  56567. });
  56568. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56569. /**
  56570. * 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.
  56571. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56572. */
  56573. get: function () {
  56574. if (this.particleEmitterType.maxEmitBox) {
  56575. return this.particleEmitterType.maxEmitBox;
  56576. }
  56577. return BABYLON.Vector3.Zero();
  56578. },
  56579. set: function (value) {
  56580. if (this.particleEmitterType.maxEmitBox) {
  56581. this.particleEmitterType.maxEmitBox = value;
  56582. }
  56583. },
  56584. enumerable: true,
  56585. configurable: true
  56586. });
  56587. /**
  56588. * Gets the maximum number of particles active at the same time.
  56589. * @returns The max number of active particles.
  56590. */
  56591. GPUParticleSystem.prototype.getCapacity = function () {
  56592. return this._capacity;
  56593. };
  56594. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56595. /**
  56596. * Gets or set the number of active particles
  56597. */
  56598. get: function () {
  56599. return this._activeCount;
  56600. },
  56601. set: function (value) {
  56602. this._activeCount = Math.min(value, this._capacity);
  56603. },
  56604. enumerable: true,
  56605. configurable: true
  56606. });
  56607. /**
  56608. * Is this system ready to be used/rendered
  56609. * @return true if the system is ready
  56610. */
  56611. GPUParticleSystem.prototype.isReady = function () {
  56612. if (!this._updateEffect) {
  56613. this._recreateUpdateEffect();
  56614. this._recreateRenderEffect();
  56615. return false;
  56616. }
  56617. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56618. return false;
  56619. }
  56620. return true;
  56621. };
  56622. /**
  56623. * Gets Wether the system has been started.
  56624. * @returns True if it has been started, otherwise false.
  56625. */
  56626. GPUParticleSystem.prototype.isStarted = function () {
  56627. return this._started;
  56628. };
  56629. /**
  56630. * Starts the particle system and begins to emit.
  56631. */
  56632. GPUParticleSystem.prototype.start = function () {
  56633. this._started = true;
  56634. this._stopped = false;
  56635. };
  56636. /**
  56637. * Stops the particle system.
  56638. */
  56639. GPUParticleSystem.prototype.stop = function () {
  56640. this._stopped = true;
  56641. };
  56642. /**
  56643. * Remove all active particles
  56644. */
  56645. GPUParticleSystem.prototype.reset = function () {
  56646. this._releaseBuffers();
  56647. this._releaseVAOs();
  56648. this._currentActiveCount = 0;
  56649. this._targetIndex = 0;
  56650. };
  56651. /**
  56652. * Returns the string "GPUParticleSystem"
  56653. * @returns a string containing the class name
  56654. */
  56655. GPUParticleSystem.prototype.getClassName = function () {
  56656. return "GPUParticleSystem";
  56657. };
  56658. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56659. var updateVertexBuffers = {};
  56660. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56661. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56662. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56663. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56664. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3);
  56665. updateVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4);
  56666. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 13, 3);
  56667. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2);
  56668. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56669. this._engine.bindArrayBuffer(null);
  56670. return vao;
  56671. };
  56672. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56673. var renderVertexBuffers = {};
  56674. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56675. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56676. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56677. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3, this._attributesStrideSize, true);
  56678. renderVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4, this._attributesStrideSize, true);
  56679. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2, this._attributesStrideSize, true);
  56680. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56681. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56682. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56683. this._engine.bindArrayBuffer(null);
  56684. return vao;
  56685. };
  56686. GPUParticleSystem.prototype._initialize = function (force) {
  56687. if (force === void 0) { force = false; }
  56688. if (this._buffer0 && !force) {
  56689. return;
  56690. }
  56691. var engine = this._scene.getEngine();
  56692. var data = new Array();
  56693. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56694. // position
  56695. data.push(0.0);
  56696. data.push(0.0);
  56697. data.push(0.0);
  56698. // Age and life
  56699. data.push(0.0); // create the particle as a dead one to create a new one at start
  56700. data.push(0.0);
  56701. // Seed
  56702. data.push(Math.random());
  56703. // Size
  56704. data.push(0.0);
  56705. data.push(0.0);
  56706. data.push(0.0);
  56707. // color
  56708. data.push(0.0);
  56709. data.push(0.0);
  56710. data.push(0.0);
  56711. data.push(0.0);
  56712. // direction
  56713. data.push(0.0);
  56714. data.push(0.0);
  56715. data.push(0.0);
  56716. // angle
  56717. data.push(0.0);
  56718. data.push(0.0);
  56719. }
  56720. // Sprite data
  56721. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56722. -0.5, 0.5, 0, 1,
  56723. -0.5, -0.5, 0, 0,
  56724. 0.5, -0.5, 1, 0]);
  56725. // Buffers
  56726. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56727. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56728. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56729. // Update VAO
  56730. this._updateVAO = [];
  56731. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56732. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56733. // Render VAO
  56734. this._renderVAO = [];
  56735. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56736. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56737. // Links
  56738. this._sourceBuffer = this._buffer0;
  56739. this._targetBuffer = this._buffer1;
  56740. };
  56741. /** @hidden */
  56742. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56743. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56744. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56745. return;
  56746. }
  56747. this._updateEffectOptions.defines = defines;
  56748. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56749. };
  56750. /** @hidden */
  56751. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56752. var defines = "";
  56753. if (this._scene.clipPlane) {
  56754. defines = "\n#define CLIPPLANE";
  56755. }
  56756. if (this._renderEffect && this._renderEffect.defines === defines) {
  56757. return;
  56758. }
  56759. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56760. };
  56761. /**
  56762. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56763. */
  56764. GPUParticleSystem.prototype.animate = function () {
  56765. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  56766. this._actualFrame += this._timeDelta;
  56767. if (!this._stopped) {
  56768. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  56769. this.stop();
  56770. }
  56771. }
  56772. };
  56773. /**
  56774. * Renders the particle system in its current state.
  56775. * @returns the current number of particles
  56776. */
  56777. GPUParticleSystem.prototype.render = function () {
  56778. if (!this._started) {
  56779. return 0;
  56780. }
  56781. this._recreateUpdateEffect();
  56782. this._recreateRenderEffect();
  56783. if (!this.isReady()) {
  56784. return 0;
  56785. }
  56786. if (this._currentRenderId === this._scene.getRenderId()) {
  56787. return 0;
  56788. }
  56789. this._currentRenderId = this._scene.getRenderId();
  56790. // Get everything ready to render
  56791. this._initialize();
  56792. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  56793. // Enable update effect
  56794. this._engine.enableEffect(this._updateEffect);
  56795. this._engine.setState(false);
  56796. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  56797. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  56798. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  56799. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  56800. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  56801. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  56802. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  56803. this._updateEffect.setDirectColor4("color1", this.color1);
  56804. this._updateEffect.setDirectColor4("color2", this.color2);
  56805. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  56806. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  56807. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  56808. this._updateEffect.setVector3("gravity", this.gravity);
  56809. if (this.particleEmitterType) {
  56810. this.particleEmitterType.applyToShader(this._updateEffect);
  56811. }
  56812. var emitterWM;
  56813. if (this.emitter.position) {
  56814. var emitterMesh = this.emitter;
  56815. emitterWM = emitterMesh.getWorldMatrix();
  56816. }
  56817. else {
  56818. var emitterPosition = this.emitter;
  56819. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56820. }
  56821. this._updateEffect.setMatrix("emitterWM", emitterWM);
  56822. // Bind source VAO
  56823. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  56824. // Update
  56825. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  56826. this._engine.setRasterizerState(false);
  56827. this._engine.beginTransformFeedback();
  56828. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  56829. this._engine.endTransformFeedback();
  56830. this._engine.setRasterizerState(true);
  56831. this._engine.bindTransformFeedbackBuffer(null);
  56832. // Enable render effect
  56833. this._engine.enableEffect(this._renderEffect);
  56834. var viewMatrix = this._scene.getViewMatrix();
  56835. this._renderEffect.setMatrix("view", viewMatrix);
  56836. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  56837. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  56838. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  56839. if (this._scene.clipPlane) {
  56840. var clipPlane = this._scene.clipPlane;
  56841. var invView = viewMatrix.clone();
  56842. invView.invert();
  56843. this._renderEffect.setMatrix("invView", invView);
  56844. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56845. }
  56846. // Draw order
  56847. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  56848. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56849. }
  56850. else {
  56851. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56852. }
  56853. if (this.forceDepthWrite) {
  56854. this._engine.setDepthWrite(true);
  56855. }
  56856. // Bind source VAO
  56857. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  56858. // Render
  56859. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  56860. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56861. // Switch VAOs
  56862. this._targetIndex++;
  56863. if (this._targetIndex === 2) {
  56864. this._targetIndex = 0;
  56865. }
  56866. // Switch buffers
  56867. var tmpBuffer = this._sourceBuffer;
  56868. this._sourceBuffer = this._targetBuffer;
  56869. this._targetBuffer = tmpBuffer;
  56870. return this._currentActiveCount;
  56871. };
  56872. /**
  56873. * Rebuilds the particle system
  56874. */
  56875. GPUParticleSystem.prototype.rebuild = function () {
  56876. this._initialize(true);
  56877. };
  56878. GPUParticleSystem.prototype._releaseBuffers = function () {
  56879. if (this._buffer0) {
  56880. this._buffer0.dispose();
  56881. this._buffer0 = null;
  56882. }
  56883. if (this._buffer1) {
  56884. this._buffer1.dispose();
  56885. this._buffer1 = null;
  56886. }
  56887. if (this._spriteBuffer) {
  56888. this._spriteBuffer.dispose();
  56889. this._spriteBuffer = null;
  56890. }
  56891. };
  56892. GPUParticleSystem.prototype._releaseVAOs = function () {
  56893. if (!this._updateVAO) {
  56894. return;
  56895. }
  56896. for (var index = 0; index < this._updateVAO.length; index++) {
  56897. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  56898. }
  56899. this._updateVAO = [];
  56900. for (var index = 0; index < this._renderVAO.length; index++) {
  56901. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  56902. }
  56903. this._renderVAO = [];
  56904. };
  56905. /**
  56906. * Disposes the particle system and free the associated resources
  56907. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56908. */
  56909. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  56910. if (disposeTexture === void 0) { disposeTexture = true; }
  56911. var index = this._scene.particleSystems.indexOf(this);
  56912. if (index > -1) {
  56913. this._scene.particleSystems.splice(index, 1);
  56914. }
  56915. this._releaseBuffers();
  56916. this._releaseVAOs();
  56917. if (this._randomTexture) {
  56918. this._randomTexture.dispose();
  56919. this._randomTexture = null;
  56920. }
  56921. if (disposeTexture && this.particleTexture) {
  56922. this.particleTexture.dispose();
  56923. this.particleTexture = null;
  56924. }
  56925. // Callback
  56926. this.onDisposeObservable.notifyObservers(this);
  56927. this.onDisposeObservable.clear();
  56928. };
  56929. /**
  56930. * Clones the particle system.
  56931. * @param name The name of the cloned object
  56932. * @param newEmitter The new emitter to use
  56933. * @returns the cloned particle system
  56934. */
  56935. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  56936. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  56937. BABYLON.Tools.DeepCopy(this, result);
  56938. if (newEmitter === undefined) {
  56939. newEmitter = this.emitter;
  56940. }
  56941. result.emitter = newEmitter;
  56942. if (this.particleTexture) {
  56943. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56944. }
  56945. return result;
  56946. };
  56947. /**
  56948. * Serializes the particle system to a JSON object.
  56949. * @returns the JSON object
  56950. */
  56951. GPUParticleSystem.prototype.serialize = function () {
  56952. var serializationObject = {};
  56953. serializationObject.name = this.name;
  56954. serializationObject.id = this.id;
  56955. // Emitter
  56956. if (this.emitter.position) {
  56957. var emitterMesh = this.emitter;
  56958. serializationObject.emitterId = emitterMesh.id;
  56959. }
  56960. else {
  56961. var emitterPosition = this.emitter;
  56962. serializationObject.emitter = emitterPosition.asArray();
  56963. }
  56964. serializationObject.capacity = this.getCapacity();
  56965. if (this.particleTexture) {
  56966. serializationObject.textureName = this.particleTexture.name;
  56967. }
  56968. // Animations
  56969. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56970. // Particle system
  56971. serializationObject.activeParticleCount = this.activeParticleCount;
  56972. serializationObject.randomTextureSize = this._randomTextureSize;
  56973. serializationObject.minSize = this.minSize;
  56974. serializationObject.maxSize = this.maxSize;
  56975. serializationObject.minEmitPower = this.minEmitPower;
  56976. serializationObject.maxEmitPower = this.maxEmitPower;
  56977. serializationObject.minLifeTime = this.minLifeTime;
  56978. serializationObject.maxLifeTime = this.maxLifeTime;
  56979. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56980. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56981. serializationObject.emitRate = this.emitRate;
  56982. serializationObject.gravity = this.gravity.asArray();
  56983. serializationObject.color1 = this.color1.asArray();
  56984. serializationObject.color2 = this.color2.asArray();
  56985. serializationObject.colorDead = this.colorDead.asArray();
  56986. serializationObject.updateSpeed = this.updateSpeed;
  56987. serializationObject.targetStopDuration = this.targetStopDuration;
  56988. serializationObject.blendMode = this.blendMode;
  56989. // Emitter
  56990. if (this.particleEmitterType) {
  56991. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56992. }
  56993. return serializationObject;
  56994. };
  56995. /**
  56996. * Parses a JSON object to create a GPU particle system.
  56997. * @param parsedParticleSystem The JSON object to parse
  56998. * @param scene The scene to create the particle system in
  56999. * @param rootUrl The root url to use to load external dependencies like texture
  57000. * @returns the parsed GPU particle system
  57001. */
  57002. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57003. var name = parsedParticleSystem.name;
  57004. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57005. if (parsedParticleSystem.id) {
  57006. particleSystem.id = parsedParticleSystem.id;
  57007. }
  57008. // Texture
  57009. if (parsedParticleSystem.textureName) {
  57010. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57011. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57012. }
  57013. // Emitter
  57014. if (parsedParticleSystem.emitterId) {
  57015. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57016. }
  57017. else {
  57018. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57019. }
  57020. // Animations
  57021. if (parsedParticleSystem.animations) {
  57022. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57023. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57024. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57025. }
  57026. }
  57027. // Particle system
  57028. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57029. particleSystem.minSize = parsedParticleSystem.minSize;
  57030. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57031. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57032. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57033. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57034. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57035. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57036. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57037. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57038. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57039. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57040. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57041. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57042. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57043. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57044. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57045. // Emitter
  57046. if (parsedParticleSystem.particleEmitterType) {
  57047. var emitterType = void 0;
  57048. switch (parsedParticleSystem.particleEmitterType.type) {
  57049. case "SphereEmitter":
  57050. emitterType = new BABYLON.SphereParticleEmitter();
  57051. break;
  57052. case "SphereDirectedParticleEmitter":
  57053. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57054. break;
  57055. case "ConeEmitter":
  57056. emitterType = new BABYLON.ConeParticleEmitter();
  57057. break;
  57058. case "BoxEmitter":
  57059. default:
  57060. emitterType = new BABYLON.BoxParticleEmitter();
  57061. break;
  57062. }
  57063. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57064. particleSystem.particleEmitterType = emitterType;
  57065. }
  57066. return particleSystem;
  57067. };
  57068. return GPUParticleSystem;
  57069. }());
  57070. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57071. })(BABYLON || (BABYLON = {}));
  57072. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57073. var BABYLON;
  57074. (function (BABYLON) {
  57075. /**
  57076. * Represents one particle of a solid particle system.
  57077. */
  57078. var SolidParticle = /** @class */ (function () {
  57079. /**
  57080. * Creates a Solid Particle object.
  57081. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57082. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57083. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57084. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57085. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57086. * @param shapeId (integer) is the model shape identifier in the SPS.
  57087. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57088. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57089. */
  57090. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57091. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57092. /**
  57093. * particle global index
  57094. */
  57095. this.idx = 0;
  57096. /**
  57097. * The color of the particle
  57098. */
  57099. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57100. /**
  57101. * The world space position of the particle.
  57102. */
  57103. this.position = BABYLON.Vector3.Zero();
  57104. /**
  57105. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57106. */
  57107. this.rotation = BABYLON.Vector3.Zero();
  57108. /**
  57109. * The scaling of the particle.
  57110. */
  57111. this.scaling = BABYLON.Vector3.One();
  57112. /**
  57113. * The uvs of the particle.
  57114. */
  57115. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57116. /**
  57117. * The current speed of the particle.
  57118. */
  57119. this.velocity = BABYLON.Vector3.Zero();
  57120. /**
  57121. * The pivot point in the particle local space.
  57122. */
  57123. this.pivot = BABYLON.Vector3.Zero();
  57124. /**
  57125. * Must the particle be translated from its pivot point in its local space ?
  57126. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57127. * Default : false
  57128. */
  57129. this.translateFromPivot = false;
  57130. /**
  57131. * Is the particle active or not ?
  57132. */
  57133. this.alive = true;
  57134. /**
  57135. * Is the particle visible or not ?
  57136. */
  57137. this.isVisible = true;
  57138. /**
  57139. * Index of this particle in the global "positions" array (Internal use)
  57140. */
  57141. this._pos = 0;
  57142. /**
  57143. * Index of this particle in the global "indices" array (Internal use)
  57144. */
  57145. this._ind = 0;
  57146. /**
  57147. * ModelShape id of this particle
  57148. */
  57149. this.shapeId = 0;
  57150. /**
  57151. * Index of the particle in its shape id (Internal use)
  57152. */
  57153. this.idxInShape = 0;
  57154. /**
  57155. * Still set as invisible in order to skip useless computations (Internal use)
  57156. */
  57157. this._stillInvisible = false;
  57158. /**
  57159. * Last computed particle rotation matrix
  57160. */
  57161. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57162. /**
  57163. * Parent particle Id, if any.
  57164. * Default null.
  57165. */
  57166. this.parentId = null;
  57167. /**
  57168. * Internal global position in the SPS.
  57169. */
  57170. this._globalPosition = BABYLON.Vector3.Zero();
  57171. this.idx = particleIndex;
  57172. this._pos = positionIndex;
  57173. this._ind = indiceIndex;
  57174. this._model = model;
  57175. this.shapeId = shapeId;
  57176. this.idxInShape = idxInShape;
  57177. this._sps = sps;
  57178. if (modelBoundingInfo) {
  57179. this._modelBoundingInfo = modelBoundingInfo;
  57180. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57181. }
  57182. }
  57183. Object.defineProperty(SolidParticle.prototype, "scale", {
  57184. /**
  57185. * Legacy support, changed scale to scaling
  57186. */
  57187. get: function () {
  57188. return this.scaling;
  57189. },
  57190. /**
  57191. * Legacy support, changed scale to scaling
  57192. */
  57193. set: function (scale) {
  57194. this.scaling = scale;
  57195. },
  57196. enumerable: true,
  57197. configurable: true
  57198. });
  57199. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57200. /**
  57201. * Legacy support, changed quaternion to rotationQuaternion
  57202. */
  57203. get: function () {
  57204. return this.rotationQuaternion;
  57205. },
  57206. /**
  57207. * Legacy support, changed quaternion to rotationQuaternion
  57208. */
  57209. set: function (q) {
  57210. this.rotationQuaternion = q;
  57211. },
  57212. enumerable: true,
  57213. configurable: true
  57214. });
  57215. /**
  57216. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57217. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57218. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57219. * @returns true if it intersects
  57220. */
  57221. SolidParticle.prototype.intersectsMesh = function (target) {
  57222. if (!this._boundingInfo || !target._boundingInfo) {
  57223. return false;
  57224. }
  57225. if (this._sps._bSphereOnly) {
  57226. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57227. }
  57228. return this._boundingInfo.intersects(target._boundingInfo, false);
  57229. };
  57230. return SolidParticle;
  57231. }());
  57232. BABYLON.SolidParticle = SolidParticle;
  57233. /**
  57234. * Represents the shape of the model used by one particle of a solid particle system.
  57235. * SPS internal tool, don't use it manually.
  57236. */
  57237. var ModelShape = /** @class */ (function () {
  57238. /**
  57239. * 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.
  57240. * SPS internal tool, don't use it manually.
  57241. * @hidden
  57242. */
  57243. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57244. /**
  57245. * length of the shape in the model indices array (internal use)
  57246. */
  57247. this._indicesLength = 0;
  57248. this.shapeID = id;
  57249. this._shape = shape;
  57250. this._indicesLength = indicesLength;
  57251. this._shapeUV = shapeUV;
  57252. this._positionFunction = posFunction;
  57253. this._vertexFunction = vtxFunction;
  57254. }
  57255. return ModelShape;
  57256. }());
  57257. BABYLON.ModelShape = ModelShape;
  57258. /**
  57259. * Represents a Depth Sorted Particle in the solid particle system.
  57260. */
  57261. var DepthSortedParticle = /** @class */ (function () {
  57262. function DepthSortedParticle() {
  57263. /**
  57264. * Index of the particle in the "indices" array
  57265. */
  57266. this.ind = 0;
  57267. /**
  57268. * Length of the particle shape in the "indices" array
  57269. */
  57270. this.indicesLength = 0;
  57271. /**
  57272. * Squared distance from the particle to the camera
  57273. */
  57274. this.sqDistance = 0.0;
  57275. }
  57276. return DepthSortedParticle;
  57277. }());
  57278. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57279. })(BABYLON || (BABYLON = {}));
  57280. //# sourceMappingURL=babylon.solidParticle.js.map
  57281. var BABYLON;
  57282. (function (BABYLON) {
  57283. /**
  57284. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57285. *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.
  57286. * The SPS is also a particle system. It provides some methods to manage the particles.
  57287. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57288. *
  57289. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57290. */
  57291. var SolidParticleSystem = /** @class */ (function () {
  57292. /**
  57293. * Creates a SPS (Solid Particle System) object.
  57294. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57295. * @param scene (Scene) is the scene in which the SPS is added.
  57296. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57297. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57298. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57299. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57300. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57301. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57302. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57303. */
  57304. function SolidParticleSystem(name, scene, options) {
  57305. /**
  57306. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57307. * Example : var p = SPS.particles[i];
  57308. */
  57309. this.particles = new Array();
  57310. /**
  57311. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57312. */
  57313. this.nbParticles = 0;
  57314. /**
  57315. * If the particles must ever face the camera (default false). Useful for planar particles.
  57316. */
  57317. this.billboard = false;
  57318. /**
  57319. * Recompute normals when adding a shape
  57320. */
  57321. this.recomputeNormals = true;
  57322. /**
  57323. * This a counter ofr your own usage. It's not set by any SPS functions.
  57324. */
  57325. this.counter = 0;
  57326. /**
  57327. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57328. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57329. */
  57330. this.vars = {};
  57331. /**
  57332. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57333. */
  57334. this._bSphereOnly = false;
  57335. /**
  57336. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57337. */
  57338. this._bSphereRadiusFactor = 1.0;
  57339. this._positions = new Array();
  57340. this._indices = new Array();
  57341. this._normals = new Array();
  57342. this._colors = new Array();
  57343. this._uvs = new Array();
  57344. this._index = 0; // indices index
  57345. this._updatable = true;
  57346. this._pickable = false;
  57347. this._isVisibilityBoxLocked = false;
  57348. this._alwaysVisible = false;
  57349. this._depthSort = false;
  57350. this._shapeCounter = 0;
  57351. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57352. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57353. this._computeParticleColor = true;
  57354. this._computeParticleTexture = true;
  57355. this._computeParticleRotation = true;
  57356. this._computeParticleVertex = false;
  57357. this._computeBoundingBox = false;
  57358. this._depthSortParticles = true;
  57359. this._cam_axisZ = BABYLON.Vector3.Zero();
  57360. this._cam_axisY = BABYLON.Vector3.Zero();
  57361. this._cam_axisX = BABYLON.Vector3.Zero();
  57362. this._axisZ = BABYLON.Axis.Z;
  57363. this._camDir = BABYLON.Vector3.Zero();
  57364. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57365. this._rotMatrix = new BABYLON.Matrix();
  57366. this._invertMatrix = new BABYLON.Matrix();
  57367. this._rotated = BABYLON.Vector3.Zero();
  57368. this._quaternion = new BABYLON.Quaternion();
  57369. this._vertex = BABYLON.Vector3.Zero();
  57370. this._normal = BABYLON.Vector3.Zero();
  57371. this._yaw = 0.0;
  57372. this._pitch = 0.0;
  57373. this._roll = 0.0;
  57374. this._halfroll = 0.0;
  57375. this._halfpitch = 0.0;
  57376. this._halfyaw = 0.0;
  57377. this._sinRoll = 0.0;
  57378. this._cosRoll = 0.0;
  57379. this._sinPitch = 0.0;
  57380. this._cosPitch = 0.0;
  57381. this._sinYaw = 0.0;
  57382. this._cosYaw = 0.0;
  57383. this._mustUnrotateFixedNormals = false;
  57384. this._minimum = BABYLON.Vector3.Zero();
  57385. this._maximum = BABYLON.Vector3.Zero();
  57386. this._minBbox = BABYLON.Vector3.Zero();
  57387. this._maxBbox = BABYLON.Vector3.Zero();
  57388. this._particlesIntersect = false;
  57389. this._depthSortFunction = function (p1, p2) {
  57390. return (p2.sqDistance - p1.sqDistance);
  57391. };
  57392. this._needs32Bits = false;
  57393. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57394. this._scaledPivot = BABYLON.Vector3.Zero();
  57395. this._particleHasParent = false;
  57396. this.name = name;
  57397. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57398. this._camera = scene.activeCamera;
  57399. this._pickable = options ? options.isPickable : false;
  57400. this._depthSort = options ? options.enableDepthSort : false;
  57401. this._particlesIntersect = options ? options.particleIntersection : false;
  57402. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57403. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57404. if (options && options.updatable !== undefined) {
  57405. this._updatable = options.updatable;
  57406. }
  57407. else {
  57408. this._updatable = true;
  57409. }
  57410. if (this._pickable) {
  57411. this.pickedParticles = [];
  57412. }
  57413. if (this._depthSort) {
  57414. this.depthSortedParticles = [];
  57415. }
  57416. }
  57417. /**
  57418. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57419. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57420. * @returns the created mesh
  57421. */
  57422. SolidParticleSystem.prototype.buildMesh = function () {
  57423. if (this.nbParticles === 0) {
  57424. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57425. this.addShape(triangle, 1);
  57426. triangle.dispose();
  57427. }
  57428. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57429. this._positions32 = new Float32Array(this._positions);
  57430. this._uvs32 = new Float32Array(this._uvs);
  57431. this._colors32 = new Float32Array(this._colors);
  57432. if (this.recomputeNormals) {
  57433. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57434. }
  57435. this._normals32 = new Float32Array(this._normals);
  57436. this._fixedNormal32 = new Float32Array(this._normals);
  57437. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57438. this._unrotateFixedNormals();
  57439. }
  57440. var vertexData = new BABYLON.VertexData();
  57441. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57442. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57443. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57444. if (this._uvs32.length > 0) {
  57445. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57446. }
  57447. if (this._colors32.length > 0) {
  57448. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57449. }
  57450. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57451. vertexData.applyToMesh(mesh, this._updatable);
  57452. this.mesh = mesh;
  57453. this.mesh.isPickable = this._pickable;
  57454. // free memory
  57455. if (!this._depthSort) {
  57456. this._indices = null;
  57457. }
  57458. this._positions = null;
  57459. this._normals = null;
  57460. this._uvs = null;
  57461. this._colors = null;
  57462. if (!this._updatable) {
  57463. this.particles.length = 0;
  57464. }
  57465. return mesh;
  57466. };
  57467. /**
  57468. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57469. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57470. * Thus the particles generated from `digest()` have their property `position` set yet.
  57471. * @param mesh ( Mesh ) is the mesh to be digested
  57472. * @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
  57473. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57474. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57475. * @returns the current SPS
  57476. */
  57477. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57478. var size = (options && options.facetNb) || 1;
  57479. var number = (options && options.number) || 0;
  57480. var delta = (options && options.delta) || 0;
  57481. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57482. var meshInd = mesh.getIndices();
  57483. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57484. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57485. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57486. var f = 0; // facet counter
  57487. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57488. // compute size from number
  57489. if (number) {
  57490. number = (number > totalFacets) ? totalFacets : number;
  57491. size = Math.round(totalFacets / number);
  57492. delta = 0;
  57493. }
  57494. else {
  57495. size = (size > totalFacets) ? totalFacets : size;
  57496. }
  57497. var facetPos = []; // submesh positions
  57498. var facetInd = []; // submesh indices
  57499. var facetUV = []; // submesh UV
  57500. var facetCol = []; // submesh colors
  57501. var barycenter = BABYLON.Vector3.Zero();
  57502. var sizeO = size;
  57503. while (f < totalFacets) {
  57504. size = sizeO + Math.floor((1 + delta) * Math.random());
  57505. if (f > totalFacets - size) {
  57506. size = totalFacets - f;
  57507. }
  57508. // reset temp arrays
  57509. facetPos.length = 0;
  57510. facetInd.length = 0;
  57511. facetUV.length = 0;
  57512. facetCol.length = 0;
  57513. // iterate over "size" facets
  57514. var fi = 0;
  57515. for (var j = f * 3; j < (f + size) * 3; j++) {
  57516. facetInd.push(fi);
  57517. var i = meshInd[j];
  57518. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57519. if (meshUV) {
  57520. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57521. }
  57522. if (meshCol) {
  57523. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57524. }
  57525. fi++;
  57526. }
  57527. // create a model shape for each single particle
  57528. var idx = this.nbParticles;
  57529. var shape = this._posToShape(facetPos);
  57530. var shapeUV = this._uvsToShapeUV(facetUV);
  57531. // compute the barycenter of the shape
  57532. var v;
  57533. for (v = 0; v < shape.length; v++) {
  57534. barycenter.addInPlace(shape[v]);
  57535. }
  57536. barycenter.scaleInPlace(1 / shape.length);
  57537. // shift the shape from its barycenter to the origin
  57538. for (v = 0; v < shape.length; v++) {
  57539. shape[v].subtractInPlace(barycenter);
  57540. }
  57541. var bInfo;
  57542. if (this._particlesIntersect) {
  57543. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57544. }
  57545. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57546. // add the particle in the SPS
  57547. var currentPos = this._positions.length;
  57548. var currentInd = this._indices.length;
  57549. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57550. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57551. // initialize the particle position
  57552. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57553. this._index += shape.length;
  57554. idx++;
  57555. this.nbParticles++;
  57556. this._shapeCounter++;
  57557. f += size;
  57558. }
  57559. return this;
  57560. };
  57561. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57562. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57563. var index = 0;
  57564. var idx = 0;
  57565. for (var p = 0; p < this.particles.length; p++) {
  57566. this._particle = this.particles[p];
  57567. this._shape = this._particle._model._shape;
  57568. if (this._particle.rotationQuaternion) {
  57569. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57570. }
  57571. else {
  57572. this._yaw = this._particle.rotation.y;
  57573. this._pitch = this._particle.rotation.x;
  57574. this._roll = this._particle.rotation.z;
  57575. this._quaternionRotationYPR();
  57576. }
  57577. this._quaternionToRotationMatrix();
  57578. this._rotMatrix.invertToRef(this._invertMatrix);
  57579. for (var pt = 0; pt < this._shape.length; pt++) {
  57580. idx = index + pt * 3;
  57581. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57582. this._fixedNormal32[idx] = this._normal.x;
  57583. this._fixedNormal32[idx + 1] = this._normal.y;
  57584. this._fixedNormal32[idx + 2] = this._normal.z;
  57585. }
  57586. index = idx + 3;
  57587. }
  57588. };
  57589. //reset copy
  57590. SolidParticleSystem.prototype._resetCopy = function () {
  57591. this._copy.position.x = 0;
  57592. this._copy.position.y = 0;
  57593. this._copy.position.z = 0;
  57594. this._copy.rotation.x = 0;
  57595. this._copy.rotation.y = 0;
  57596. this._copy.rotation.z = 0;
  57597. this._copy.rotationQuaternion = null;
  57598. this._copy.scaling.x = 1.0;
  57599. this._copy.scaling.y = 1.0;
  57600. this._copy.scaling.z = 1.0;
  57601. this._copy.uvs.x = 0;
  57602. this._copy.uvs.y = 0;
  57603. this._copy.uvs.z = 1.0;
  57604. this._copy.uvs.w = 1.0;
  57605. this._copy.color = null;
  57606. this._copy.translateFromPivot = false;
  57607. };
  57608. // _meshBuilder : inserts the shape model in the global SPS mesh
  57609. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57610. var i;
  57611. var u = 0;
  57612. var c = 0;
  57613. var n = 0;
  57614. this._resetCopy();
  57615. if (options && options.positionFunction) { // call to custom positionFunction
  57616. options.positionFunction(this._copy, idx, idxInShape);
  57617. this._mustUnrotateFixedNormals = true;
  57618. }
  57619. if (this._copy.rotationQuaternion) {
  57620. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57621. }
  57622. else {
  57623. this._yaw = this._copy.rotation.y;
  57624. this._pitch = this._copy.rotation.x;
  57625. this._roll = this._copy.rotation.z;
  57626. this._quaternionRotationYPR();
  57627. }
  57628. this._quaternionToRotationMatrix();
  57629. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57630. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57631. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57632. if (this._copy.translateFromPivot) {
  57633. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57634. }
  57635. else {
  57636. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57637. }
  57638. for (i = 0; i < shape.length; i++) {
  57639. this._vertex.x = shape[i].x;
  57640. this._vertex.y = shape[i].y;
  57641. this._vertex.z = shape[i].z;
  57642. if (options && options.vertexFunction) {
  57643. options.vertexFunction(this._copy, this._vertex, i);
  57644. }
  57645. this._vertex.x *= this._copy.scaling.x;
  57646. this._vertex.y *= this._copy.scaling.y;
  57647. this._vertex.z *= this._copy.scaling.z;
  57648. this._vertex.x -= this._scaledPivot.x;
  57649. this._vertex.y -= this._scaledPivot.y;
  57650. this._vertex.z -= this._scaledPivot.z;
  57651. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57652. this._rotated.addInPlace(this._pivotBackTranslation);
  57653. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57654. if (meshUV) {
  57655. 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);
  57656. u += 2;
  57657. }
  57658. if (this._copy.color) {
  57659. this._color = this._copy.color;
  57660. }
  57661. else if (meshCol && meshCol[c] !== undefined) {
  57662. this._color.r = meshCol[c];
  57663. this._color.g = meshCol[c + 1];
  57664. this._color.b = meshCol[c + 2];
  57665. this._color.a = meshCol[c + 3];
  57666. }
  57667. else {
  57668. this._color.r = 1.0;
  57669. this._color.g = 1.0;
  57670. this._color.b = 1.0;
  57671. this._color.a = 1.0;
  57672. }
  57673. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57674. c += 4;
  57675. if (!this.recomputeNormals && meshNor) {
  57676. this._normal.x = meshNor[n];
  57677. this._normal.y = meshNor[n + 1];
  57678. this._normal.z = meshNor[n + 2];
  57679. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57680. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57681. n += 3;
  57682. }
  57683. }
  57684. for (i = 0; i < meshInd.length; i++) {
  57685. var current_ind = p + meshInd[i];
  57686. indices.push(current_ind);
  57687. if (current_ind > 65535) {
  57688. this._needs32Bits = true;
  57689. }
  57690. }
  57691. if (this._pickable) {
  57692. var nbfaces = meshInd.length / 3;
  57693. for (i = 0; i < nbfaces; i++) {
  57694. this.pickedParticles.push({ idx: idx, faceId: i });
  57695. }
  57696. }
  57697. if (this._depthSort) {
  57698. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57699. }
  57700. return this._copy;
  57701. };
  57702. // returns a shape array from positions array
  57703. SolidParticleSystem.prototype._posToShape = function (positions) {
  57704. var shape = [];
  57705. for (var i = 0; i < positions.length; i += 3) {
  57706. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57707. }
  57708. return shape;
  57709. };
  57710. // returns a shapeUV array from a Vector4 uvs
  57711. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57712. var shapeUV = [];
  57713. if (uvs) {
  57714. for (var i = 0; i < uvs.length; i++)
  57715. shapeUV.push(uvs[i]);
  57716. }
  57717. return shapeUV;
  57718. };
  57719. // adds a new particle object in the particles array
  57720. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57721. if (bInfo === void 0) { bInfo = null; }
  57722. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57723. this.particles.push(sp);
  57724. return sp;
  57725. };
  57726. /**
  57727. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57728. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57729. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57730. * @param nb (positive integer) the number of particles to be created from this model
  57731. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57732. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57733. * @returns the number of shapes in the system
  57734. */
  57735. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57736. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57737. var meshInd = mesh.getIndices();
  57738. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57739. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57740. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57741. var bbInfo;
  57742. if (this._particlesIntersect) {
  57743. bbInfo = mesh.getBoundingInfo();
  57744. }
  57745. var shape = this._posToShape(meshPos);
  57746. var shapeUV = this._uvsToShapeUV(meshUV);
  57747. var posfunc = options ? options.positionFunction : null;
  57748. var vtxfunc = options ? options.vertexFunction : null;
  57749. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57750. // particles
  57751. var sp;
  57752. var currentCopy;
  57753. var idx = this.nbParticles;
  57754. for (var i = 0; i < nb; i++) {
  57755. var currentPos = this._positions.length;
  57756. var currentInd = this._indices.length;
  57757. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57758. if (this._updatable) {
  57759. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57760. sp.position.copyFrom(currentCopy.position);
  57761. sp.rotation.copyFrom(currentCopy.rotation);
  57762. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57763. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57764. }
  57765. if (currentCopy.color && sp.color) {
  57766. sp.color.copyFrom(currentCopy.color);
  57767. }
  57768. sp.scaling.copyFrom(currentCopy.scaling);
  57769. sp.uvs.copyFrom(currentCopy.uvs);
  57770. }
  57771. this._index += shape.length;
  57772. idx++;
  57773. }
  57774. this.nbParticles += nb;
  57775. this._shapeCounter++;
  57776. return this._shapeCounter - 1;
  57777. };
  57778. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57779. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57780. this._resetCopy();
  57781. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  57782. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57783. }
  57784. if (this._copy.rotationQuaternion) {
  57785. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57786. }
  57787. else {
  57788. this._yaw = this._copy.rotation.y;
  57789. this._pitch = this._copy.rotation.x;
  57790. this._roll = this._copy.rotation.z;
  57791. this._quaternionRotationYPR();
  57792. }
  57793. this._quaternionToRotationMatrix();
  57794. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57795. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57796. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57797. if (this._copy.translateFromPivot) {
  57798. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57799. }
  57800. else {
  57801. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57802. }
  57803. this._shape = particle._model._shape;
  57804. for (var pt = 0; pt < this._shape.length; pt++) {
  57805. this._vertex.x = this._shape[pt].x;
  57806. this._vertex.y = this._shape[pt].y;
  57807. this._vertex.z = this._shape[pt].z;
  57808. if (particle._model._vertexFunction) {
  57809. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57810. }
  57811. this._vertex.x *= this._copy.scaling.x;
  57812. this._vertex.y *= this._copy.scaling.y;
  57813. this._vertex.z *= this._copy.scaling.z;
  57814. this._vertex.x -= this._scaledPivot.x;
  57815. this._vertex.y -= this._scaledPivot.y;
  57816. this._vertex.z -= this._scaledPivot.z;
  57817. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57818. this._rotated.addInPlace(this._pivotBackTranslation);
  57819. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57820. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57821. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57822. }
  57823. particle.position.x = 0.0;
  57824. particle.position.y = 0.0;
  57825. particle.position.z = 0.0;
  57826. particle.rotation.x = 0.0;
  57827. particle.rotation.y = 0.0;
  57828. particle.rotation.z = 0.0;
  57829. particle.rotationQuaternion = null;
  57830. particle.scaling.x = 1.0;
  57831. particle.scaling.y = 1.0;
  57832. particle.scaling.z = 1.0;
  57833. particle.uvs.x = 0.0;
  57834. particle.uvs.y = 0.0;
  57835. particle.uvs.z = 1.0;
  57836. particle.uvs.w = 1.0;
  57837. particle.pivot.x = 0.0;
  57838. particle.pivot.y = 0.0;
  57839. particle.pivot.z = 0.0;
  57840. particle.translateFromPivot = false;
  57841. particle.parentId = null;
  57842. };
  57843. /**
  57844. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57845. * @returns the SPS.
  57846. */
  57847. SolidParticleSystem.prototype.rebuildMesh = function () {
  57848. for (var p = 0; p < this.particles.length; p++) {
  57849. this._rebuildParticle(this.particles[p]);
  57850. }
  57851. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57852. return this;
  57853. };
  57854. /**
  57855. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57856. * This method calls `updateParticle()` for each particle of the SPS.
  57857. * For an animated SPS, it is usually called within the render loop.
  57858. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57859. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57860. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57861. * @returns the SPS.
  57862. */
  57863. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57864. if (start === void 0) { start = 0; }
  57865. if (end === void 0) { end = this.nbParticles - 1; }
  57866. if (update === void 0) { update = true; }
  57867. if (!this._updatable) {
  57868. return this;
  57869. }
  57870. // custom beforeUpdate
  57871. this.beforeUpdateParticles(start, end, update);
  57872. this._cam_axisX.x = 1.0;
  57873. this._cam_axisX.y = 0.0;
  57874. this._cam_axisX.z = 0.0;
  57875. this._cam_axisY.x = 0.0;
  57876. this._cam_axisY.y = 1.0;
  57877. this._cam_axisY.z = 0.0;
  57878. this._cam_axisZ.x = 0.0;
  57879. this._cam_axisZ.y = 0.0;
  57880. this._cam_axisZ.z = 1.0;
  57881. // cases when the World Matrix is to be computed first
  57882. if (this.billboard || this._depthSort) {
  57883. this.mesh.computeWorldMatrix(true);
  57884. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  57885. }
  57886. // if the particles will always face the camera
  57887. if (this.billboard) {
  57888. // compute the camera position and un-rotate it by the current mesh rotation
  57889. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  57890. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57891. this._cam_axisZ.normalize();
  57892. // same for camera up vector extracted from the cam view matrix
  57893. var view = this._camera.getViewMatrix(true);
  57894. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  57895. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57896. this._cam_axisY.normalize();
  57897. this._cam_axisX.normalize();
  57898. }
  57899. // if depthSort, compute the camera global position in the mesh local system
  57900. if (this._depthSort) {
  57901. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  57902. }
  57903. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57904. var idx = 0; // current position index in the global array positions32
  57905. var index = 0; // position start index in the global array positions32 of the current particle
  57906. var colidx = 0; // current color index in the global array colors32
  57907. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  57908. var uvidx = 0; // current uv index in the global array uvs32
  57909. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  57910. var pt = 0; // current index in the particle model shape
  57911. if (this.mesh.isFacetDataEnabled) {
  57912. this._computeBoundingBox = true;
  57913. }
  57914. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  57915. if (this._computeBoundingBox) {
  57916. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  57917. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57918. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57919. }
  57920. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  57921. if (this.mesh._boundingInfo) {
  57922. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  57923. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  57924. }
  57925. }
  57926. }
  57927. // particle loop
  57928. index = this.particles[start]._pos;
  57929. var vpos = (index / 3) | 0;
  57930. colorIndex = vpos * 4;
  57931. uvIndex = vpos * 2;
  57932. for (var p = start; p <= end; p++) {
  57933. this._particle = this.particles[p];
  57934. this._shape = this._particle._model._shape;
  57935. this._shapeUV = this._particle._model._shapeUV;
  57936. // call to custom user function to update the particle properties
  57937. this.updateParticle(this._particle);
  57938. // camera-particle distance for depth sorting
  57939. if (this._depthSort && this._depthSortParticles) {
  57940. var dsp = this.depthSortedParticles[p];
  57941. dsp.ind = this._particle._ind;
  57942. dsp.indicesLength = this._particle._model._indicesLength;
  57943. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  57944. }
  57945. // skip the computations for inactive or already invisible particles
  57946. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  57947. // increment indexes for the next particle
  57948. pt = this._shape.length;
  57949. index += pt * 3;
  57950. colorIndex += pt * 4;
  57951. uvIndex += pt * 2;
  57952. continue;
  57953. }
  57954. if (this._particle.isVisible) {
  57955. this._particle._stillInvisible = false; // un-mark permanent invisibility
  57956. this._particleHasParent = (this._particle.parentId !== null);
  57957. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57958. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57959. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57960. // particle rotation matrix
  57961. if (this.billboard) {
  57962. this._particle.rotation.x = 0.0;
  57963. this._particle.rotation.y = 0.0;
  57964. }
  57965. if (this._computeParticleRotation || this.billboard) {
  57966. if (this._particle.rotationQuaternion) {
  57967. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57968. }
  57969. else {
  57970. this._yaw = this._particle.rotation.y;
  57971. this._pitch = this._particle.rotation.x;
  57972. this._roll = this._particle.rotation.z;
  57973. this._quaternionRotationYPR();
  57974. }
  57975. this._quaternionToRotationMatrix();
  57976. }
  57977. if (this._particleHasParent) {
  57978. this._parent = this.particles[this._particle.parentId];
  57979. 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];
  57980. 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];
  57981. 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];
  57982. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  57983. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  57984. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  57985. if (this._computeParticleRotation || this.billboard) {
  57986. 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];
  57987. 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];
  57988. 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];
  57989. 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];
  57990. 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];
  57991. 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];
  57992. 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];
  57993. 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];
  57994. 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];
  57995. }
  57996. }
  57997. else {
  57998. this._particle._globalPosition.x = this._particle.position.x;
  57999. this._particle._globalPosition.y = this._particle.position.y;
  58000. this._particle._globalPosition.z = this._particle.position.z;
  58001. if (this._computeParticleRotation || this.billboard) {
  58002. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58003. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58004. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58005. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58006. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58007. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58008. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58009. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58010. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58011. }
  58012. }
  58013. if (this._particle.translateFromPivot) {
  58014. this._pivotBackTranslation.x = 0.0;
  58015. this._pivotBackTranslation.y = 0.0;
  58016. this._pivotBackTranslation.z = 0.0;
  58017. }
  58018. else {
  58019. this._pivotBackTranslation.x = this._scaledPivot.x;
  58020. this._pivotBackTranslation.y = this._scaledPivot.y;
  58021. this._pivotBackTranslation.z = this._scaledPivot.z;
  58022. }
  58023. // particle vertex loop
  58024. for (pt = 0; pt < this._shape.length; pt++) {
  58025. idx = index + pt * 3;
  58026. colidx = colorIndex + pt * 4;
  58027. uvidx = uvIndex + pt * 2;
  58028. this._vertex.x = this._shape[pt].x;
  58029. this._vertex.y = this._shape[pt].y;
  58030. this._vertex.z = this._shape[pt].z;
  58031. if (this._computeParticleVertex) {
  58032. this.updateParticleVertex(this._particle, this._vertex, pt);
  58033. }
  58034. // positions
  58035. this._vertex.x *= this._particle.scaling.x;
  58036. this._vertex.y *= this._particle.scaling.y;
  58037. this._vertex.z *= this._particle.scaling.z;
  58038. this._vertex.x -= this._scaledPivot.x;
  58039. this._vertex.y -= this._scaledPivot.y;
  58040. this._vertex.z -= this._scaledPivot.z;
  58041. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58042. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58043. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58044. this._rotated.x += this._pivotBackTranslation.x;
  58045. this._rotated.y += this._pivotBackTranslation.y;
  58046. this._rotated.z += this._pivotBackTranslation.z;
  58047. 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;
  58048. 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;
  58049. 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;
  58050. if (this._computeBoundingBox) {
  58051. if (this._positions32[idx] < this._minimum.x) {
  58052. this._minimum.x = this._positions32[idx];
  58053. }
  58054. if (this._positions32[idx] > this._maximum.x) {
  58055. this._maximum.x = this._positions32[idx];
  58056. }
  58057. if (this._positions32[idx + 1] < this._minimum.y) {
  58058. this._minimum.y = this._positions32[idx + 1];
  58059. }
  58060. if (this._positions32[idx + 1] > this._maximum.y) {
  58061. this._maximum.y = this._positions32[idx + 1];
  58062. }
  58063. if (this._positions32[idx + 2] < this._minimum.z) {
  58064. this._minimum.z = this._positions32[idx + 2];
  58065. }
  58066. if (this._positions32[idx + 2] > this._maximum.z) {
  58067. this._maximum.z = this._positions32[idx + 2];
  58068. }
  58069. }
  58070. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58071. if (!this._computeParticleVertex) {
  58072. this._normal.x = this._fixedNormal32[idx];
  58073. this._normal.y = this._fixedNormal32[idx + 1];
  58074. this._normal.z = this._fixedNormal32[idx + 2];
  58075. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58076. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58077. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58078. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58079. 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;
  58080. 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;
  58081. }
  58082. if (this._computeParticleColor && this._particle.color) {
  58083. this._colors32[colidx] = this._particle.color.r;
  58084. this._colors32[colidx + 1] = this._particle.color.g;
  58085. this._colors32[colidx + 2] = this._particle.color.b;
  58086. this._colors32[colidx + 3] = this._particle.color.a;
  58087. }
  58088. if (this._computeParticleTexture) {
  58089. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58090. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58091. }
  58092. }
  58093. }
  58094. // particle just set invisible : scaled to zero and positioned at the origin
  58095. else {
  58096. this._particle._stillInvisible = true; // mark the particle as invisible
  58097. for (pt = 0; pt < this._shape.length; pt++) {
  58098. idx = index + pt * 3;
  58099. colidx = colorIndex + pt * 4;
  58100. uvidx = uvIndex + pt * 2;
  58101. this._positions32[idx] = 0.0;
  58102. this._positions32[idx + 1] = 0.0;
  58103. this._positions32[idx + 2] = 0.0;
  58104. this._normals32[idx] = 0.0;
  58105. this._normals32[idx + 1] = 0.0;
  58106. this._normals32[idx + 2] = 0.0;
  58107. if (this._computeParticleColor && this._particle.color) {
  58108. this._colors32[colidx] = this._particle.color.r;
  58109. this._colors32[colidx + 1] = this._particle.color.g;
  58110. this._colors32[colidx + 2] = this._particle.color.b;
  58111. this._colors32[colidx + 3] = this._particle.color.a;
  58112. }
  58113. if (this._computeParticleTexture) {
  58114. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58115. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58116. }
  58117. }
  58118. }
  58119. // if the particle intersections must be computed : update the bbInfo
  58120. if (this._particlesIntersect) {
  58121. var bInfo = this._particle._boundingInfo;
  58122. var bBox = bInfo.boundingBox;
  58123. var bSphere = bInfo.boundingSphere;
  58124. if (!this._bSphereOnly) {
  58125. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58126. for (var b = 0; b < bBox.vectors.length; b++) {
  58127. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58128. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58129. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58130. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58131. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58132. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58133. 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;
  58134. 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;
  58135. 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;
  58136. }
  58137. bBox._update(this.mesh._worldMatrix);
  58138. }
  58139. // place and scale the particle bouding sphere in the SPS local system, then update it
  58140. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58141. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58142. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58143. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58144. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58145. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58146. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58147. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58148. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58149. 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));
  58150. bSphere._update(this.mesh._worldMatrix);
  58151. }
  58152. // increment indexes for the next particle
  58153. index = idx + 3;
  58154. colorIndex = colidx + 4;
  58155. uvIndex = uvidx + 2;
  58156. }
  58157. // if the VBO must be updated
  58158. if (update) {
  58159. if (this._computeParticleColor) {
  58160. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58161. }
  58162. if (this._computeParticleTexture) {
  58163. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58164. }
  58165. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58166. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58167. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58168. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58169. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58170. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58171. for (var i = 0; i < this._normals32.length; i++) {
  58172. this._fixedNormal32[i] = this._normals32[i];
  58173. }
  58174. }
  58175. if (!this.mesh.areNormalsFrozen) {
  58176. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58177. }
  58178. }
  58179. if (this._depthSort && this._depthSortParticles) {
  58180. this.depthSortedParticles.sort(this._depthSortFunction);
  58181. var dspl = this.depthSortedParticles.length;
  58182. var sorted = 0;
  58183. var lind = 0;
  58184. var sind = 0;
  58185. var sid = 0;
  58186. for (sorted = 0; sorted < dspl; sorted++) {
  58187. lind = this.depthSortedParticles[sorted].indicesLength;
  58188. sind = this.depthSortedParticles[sorted].ind;
  58189. for (var i = 0; i < lind; i++) {
  58190. this._indices32[sid] = this._indices[sind + i];
  58191. sid++;
  58192. }
  58193. }
  58194. this.mesh.updateIndices(this._indices32);
  58195. }
  58196. }
  58197. if (this._computeBoundingBox) {
  58198. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58199. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58200. }
  58201. this.afterUpdateParticles(start, end, update);
  58202. return this;
  58203. };
  58204. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58205. this._halfroll = this._roll * 0.5;
  58206. this._halfpitch = this._pitch * 0.5;
  58207. this._halfyaw = this._yaw * 0.5;
  58208. this._sinRoll = Math.sin(this._halfroll);
  58209. this._cosRoll = Math.cos(this._halfroll);
  58210. this._sinPitch = Math.sin(this._halfpitch);
  58211. this._cosPitch = Math.cos(this._halfpitch);
  58212. this._sinYaw = Math.sin(this._halfyaw);
  58213. this._cosYaw = Math.cos(this._halfyaw);
  58214. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58215. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58216. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58217. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58218. };
  58219. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58220. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58221. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58222. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58223. this._rotMatrix.m[3] = 0;
  58224. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58225. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58226. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58227. this._rotMatrix.m[7] = 0;
  58228. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58229. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58230. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58231. this._rotMatrix.m[11] = 0;
  58232. this._rotMatrix.m[12] = 0;
  58233. this._rotMatrix.m[13] = 0;
  58234. this._rotMatrix.m[14] = 0;
  58235. this._rotMatrix.m[15] = 1.0;
  58236. };
  58237. /**
  58238. * Disposes the SPS.
  58239. */
  58240. SolidParticleSystem.prototype.dispose = function () {
  58241. this.mesh.dispose();
  58242. this.vars = null;
  58243. // drop references to internal big arrays for the GC
  58244. this._positions = null;
  58245. this._indices = null;
  58246. this._normals = null;
  58247. this._uvs = null;
  58248. this._colors = null;
  58249. this._indices32 = null;
  58250. this._positions32 = null;
  58251. this._normals32 = null;
  58252. this._fixedNormal32 = null;
  58253. this._uvs32 = null;
  58254. this._colors32 = null;
  58255. this.pickedParticles = null;
  58256. };
  58257. /**
  58258. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58259. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58260. * @returns the SPS.
  58261. */
  58262. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58263. if (!this._isVisibilityBoxLocked) {
  58264. this.mesh.refreshBoundingInfo();
  58265. }
  58266. return this;
  58267. };
  58268. /**
  58269. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58270. * @param size the size (float) of the visibility box
  58271. * note : this doesn't lock the SPS mesh bounding box.
  58272. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58273. */
  58274. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58275. var vis = size / 2;
  58276. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58277. };
  58278. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58279. /**
  58280. * Gets whether the SPS as always visible or not
  58281. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58282. */
  58283. get: function () {
  58284. return this._alwaysVisible;
  58285. },
  58286. /**
  58287. * Sets the SPS as always visible or not
  58288. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58289. */
  58290. set: function (val) {
  58291. this._alwaysVisible = val;
  58292. this.mesh.alwaysSelectAsActiveMesh = val;
  58293. },
  58294. enumerable: true,
  58295. configurable: true
  58296. });
  58297. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58298. /**
  58299. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58300. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58301. */
  58302. get: function () {
  58303. return this._isVisibilityBoxLocked;
  58304. },
  58305. /**
  58306. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58307. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58308. */
  58309. set: function (val) {
  58310. this._isVisibilityBoxLocked = val;
  58311. var boundingInfo = this.mesh.getBoundingInfo();
  58312. boundingInfo.isLocked = val;
  58313. },
  58314. enumerable: true,
  58315. configurable: true
  58316. });
  58317. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58318. /**
  58319. * Gets if `setParticles()` computes the particle rotations or not.
  58320. * Default value : true. The SPS is faster when it's set to false.
  58321. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58322. */
  58323. get: function () {
  58324. return this._computeParticleRotation;
  58325. },
  58326. /**
  58327. * Tells to `setParticles()` to compute the particle rotations or not.
  58328. * Default value : true. The SPS is faster when it's set to false.
  58329. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58330. */
  58331. set: function (val) {
  58332. this._computeParticleRotation = val;
  58333. },
  58334. enumerable: true,
  58335. configurable: true
  58336. });
  58337. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58338. /**
  58339. * Gets if `setParticles()` computes the particle colors or not.
  58340. * Default value : true. The SPS is faster when it's set to false.
  58341. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58342. */
  58343. get: function () {
  58344. return this._computeParticleColor;
  58345. },
  58346. /**
  58347. * Tells to `setParticles()` to compute the particle colors or not.
  58348. * Default value : true. The SPS is faster when it's set to false.
  58349. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58350. */
  58351. set: function (val) {
  58352. this._computeParticleColor = val;
  58353. },
  58354. enumerable: true,
  58355. configurable: true
  58356. });
  58357. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58358. /**
  58359. * Gets if `setParticles()` computes the particle textures or not.
  58360. * Default value : true. The SPS is faster when it's set to false.
  58361. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58362. */
  58363. get: function () {
  58364. return this._computeParticleTexture;
  58365. },
  58366. set: function (val) {
  58367. this._computeParticleTexture = val;
  58368. },
  58369. enumerable: true,
  58370. configurable: true
  58371. });
  58372. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58373. /**
  58374. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58375. * Default value : false. The SPS is faster when it's set to false.
  58376. * Note : the particle custom vertex positions aren't stored values.
  58377. */
  58378. get: function () {
  58379. return this._computeParticleVertex;
  58380. },
  58381. /**
  58382. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58383. * Default value : false. The SPS is faster when it's set to false.
  58384. * Note : the particle custom vertex positions aren't stored values.
  58385. */
  58386. set: function (val) {
  58387. this._computeParticleVertex = val;
  58388. },
  58389. enumerable: true,
  58390. configurable: true
  58391. });
  58392. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58393. /**
  58394. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58395. */
  58396. get: function () {
  58397. return this._computeBoundingBox;
  58398. },
  58399. /**
  58400. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58401. */
  58402. set: function (val) {
  58403. this._computeBoundingBox = val;
  58404. },
  58405. enumerable: true,
  58406. configurable: true
  58407. });
  58408. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58409. /**
  58410. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58411. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58412. * Default : `true`
  58413. */
  58414. get: function () {
  58415. return this._depthSortParticles;
  58416. },
  58417. /**
  58418. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58419. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58420. * Default : `true`
  58421. */
  58422. set: function (val) {
  58423. this._depthSortParticles = val;
  58424. },
  58425. enumerable: true,
  58426. configurable: true
  58427. });
  58428. // =======================================================================
  58429. // Particle behavior logic
  58430. // these following methods may be overwritten by the user to fit his needs
  58431. /**
  58432. * This function does nothing. It may be overwritten to set all the particle first values.
  58433. * The SPS doesn't call this function, you may have to call it by your own.
  58434. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58435. */
  58436. SolidParticleSystem.prototype.initParticles = function () {
  58437. };
  58438. /**
  58439. * This function does nothing. It may be overwritten to recycle a particle.
  58440. * The SPS doesn't call this function, you may have to call it by your own.
  58441. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58442. * @param particle The particle to recycle
  58443. * @returns the recycled particle
  58444. */
  58445. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58446. return particle;
  58447. };
  58448. /**
  58449. * Updates a particle : this function should be overwritten by the user.
  58450. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58451. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58452. * @example : just set a particle position or velocity and recycle conditions
  58453. * @param particle The particle to update
  58454. * @returns the updated particle
  58455. */
  58456. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58457. return particle;
  58458. };
  58459. /**
  58460. * Updates a vertex of a particle : it can be overwritten by the user.
  58461. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58462. * @param particle the current particle
  58463. * @param vertex the current index of the current particle
  58464. * @param pt the index of the current vertex in the particle shape
  58465. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58466. * @example : just set a vertex particle position
  58467. * @returns the updated vertex
  58468. */
  58469. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58470. return vertex;
  58471. };
  58472. /**
  58473. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58474. * This does nothing and may be overwritten by the user.
  58475. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58476. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58477. * @param update the boolean update value actually passed to setParticles()
  58478. */
  58479. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58480. };
  58481. /**
  58482. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58483. * This will be passed three parameters.
  58484. * This does nothing and may be overwritten by the user.
  58485. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58486. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58487. * @param update the boolean update value actually passed to setParticles()
  58488. */
  58489. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58490. };
  58491. return SolidParticleSystem;
  58492. }());
  58493. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58494. })(BABYLON || (BABYLON = {}));
  58495. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58496. var BABYLON;
  58497. (function (BABYLON) {
  58498. var ShaderMaterial = /** @class */ (function (_super) {
  58499. __extends(ShaderMaterial, _super);
  58500. function ShaderMaterial(name, scene, shaderPath, options) {
  58501. var _this = _super.call(this, name, scene) || this;
  58502. _this._textures = {};
  58503. _this._textureArrays = {};
  58504. _this._floats = {};
  58505. _this._ints = {};
  58506. _this._floatsArrays = {};
  58507. _this._colors3 = {};
  58508. _this._colors3Arrays = {};
  58509. _this._colors4 = {};
  58510. _this._vectors2 = {};
  58511. _this._vectors3 = {};
  58512. _this._vectors4 = {};
  58513. _this._matrices = {};
  58514. _this._matrices3x3 = {};
  58515. _this._matrices2x2 = {};
  58516. _this._vectors2Arrays = {};
  58517. _this._vectors3Arrays = {};
  58518. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58519. _this._shaderPath = shaderPath;
  58520. options.needAlphaBlending = options.needAlphaBlending || false;
  58521. options.needAlphaTesting = options.needAlphaTesting || false;
  58522. options.attributes = options.attributes || ["position", "normal", "uv"];
  58523. options.uniforms = options.uniforms || ["worldViewProjection"];
  58524. options.uniformBuffers = options.uniformBuffers || [];
  58525. options.samplers = options.samplers || [];
  58526. options.defines = options.defines || [];
  58527. _this._options = options;
  58528. return _this;
  58529. }
  58530. ShaderMaterial.prototype.getClassName = function () {
  58531. return "ShaderMaterial";
  58532. };
  58533. ShaderMaterial.prototype.needAlphaBlending = function () {
  58534. return this._options.needAlphaBlending;
  58535. };
  58536. ShaderMaterial.prototype.needAlphaTesting = function () {
  58537. return this._options.needAlphaTesting;
  58538. };
  58539. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58540. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58541. this._options.uniforms.push(uniformName);
  58542. }
  58543. };
  58544. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58545. if (this._options.samplers.indexOf(name) === -1) {
  58546. this._options.samplers.push(name);
  58547. }
  58548. this._textures[name] = texture;
  58549. return this;
  58550. };
  58551. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58552. if (this._options.samplers.indexOf(name) === -1) {
  58553. this._options.samplers.push(name);
  58554. }
  58555. this._checkUniform(name);
  58556. this._textureArrays[name] = textures;
  58557. return this;
  58558. };
  58559. ShaderMaterial.prototype.setFloat = function (name, value) {
  58560. this._checkUniform(name);
  58561. this._floats[name] = value;
  58562. return this;
  58563. };
  58564. ShaderMaterial.prototype.setInt = function (name, value) {
  58565. this._checkUniform(name);
  58566. this._ints[name] = value;
  58567. return this;
  58568. };
  58569. ShaderMaterial.prototype.setFloats = function (name, value) {
  58570. this._checkUniform(name);
  58571. this._floatsArrays[name] = value;
  58572. return this;
  58573. };
  58574. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58575. this._checkUniform(name);
  58576. this._colors3[name] = value;
  58577. return this;
  58578. };
  58579. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58580. this._checkUniform(name);
  58581. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58582. color.toArray(arr, arr.length);
  58583. return arr;
  58584. }, []);
  58585. return this;
  58586. };
  58587. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58588. this._checkUniform(name);
  58589. this._colors4[name] = value;
  58590. return this;
  58591. };
  58592. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58593. this._checkUniform(name);
  58594. this._vectors2[name] = value;
  58595. return this;
  58596. };
  58597. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58598. this._checkUniform(name);
  58599. this._vectors3[name] = value;
  58600. return this;
  58601. };
  58602. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58603. this._checkUniform(name);
  58604. this._vectors4[name] = value;
  58605. return this;
  58606. };
  58607. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58608. this._checkUniform(name);
  58609. this._matrices[name] = value;
  58610. return this;
  58611. };
  58612. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58613. this._checkUniform(name);
  58614. this._matrices3x3[name] = value;
  58615. return this;
  58616. };
  58617. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58618. this._checkUniform(name);
  58619. this._matrices2x2[name] = value;
  58620. return this;
  58621. };
  58622. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58623. this._checkUniform(name);
  58624. this._vectors2Arrays[name] = value;
  58625. return this;
  58626. };
  58627. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58628. this._checkUniform(name);
  58629. this._vectors3Arrays[name] = value;
  58630. return this;
  58631. };
  58632. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58633. if (!mesh) {
  58634. return true;
  58635. }
  58636. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58637. return false;
  58638. }
  58639. return false;
  58640. };
  58641. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58642. var scene = this.getScene();
  58643. var engine = scene.getEngine();
  58644. if (!this.checkReadyOnEveryCall) {
  58645. if (this._renderId === scene.getRenderId()) {
  58646. if (this._checkCache(scene, mesh, useInstances)) {
  58647. return true;
  58648. }
  58649. }
  58650. }
  58651. // Instances
  58652. var defines = [];
  58653. var attribs = [];
  58654. var fallbacks = new BABYLON.EffectFallbacks();
  58655. if (useInstances) {
  58656. defines.push("#define INSTANCES");
  58657. }
  58658. for (var index = 0; index < this._options.defines.length; index++) {
  58659. defines.push(this._options.defines[index]);
  58660. }
  58661. for (var index = 0; index < this._options.attributes.length; index++) {
  58662. attribs.push(this._options.attributes[index]);
  58663. }
  58664. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58665. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58666. defines.push("#define VERTEXCOLOR");
  58667. }
  58668. // Bones
  58669. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58670. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58671. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58672. if (mesh.numBoneInfluencers > 4) {
  58673. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58674. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58675. }
  58676. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58677. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58678. fallbacks.addCPUSkinningFallback(0, mesh);
  58679. if (this._options.uniforms.indexOf("mBones") === -1) {
  58680. this._options.uniforms.push("mBones");
  58681. }
  58682. }
  58683. else {
  58684. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58685. }
  58686. // Textures
  58687. for (var name in this._textures) {
  58688. if (!this._textures[name].isReady()) {
  58689. return false;
  58690. }
  58691. }
  58692. // Alpha test
  58693. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58694. defines.push("#define ALPHATEST");
  58695. }
  58696. var previousEffect = this._effect;
  58697. var join = defines.join("\n");
  58698. this._effect = engine.createEffect(this._shaderPath, {
  58699. attributes: attribs,
  58700. uniformsNames: this._options.uniforms,
  58701. uniformBuffersNames: this._options.uniformBuffers,
  58702. samplers: this._options.samplers,
  58703. defines: join,
  58704. fallbacks: fallbacks,
  58705. onCompiled: this.onCompiled,
  58706. onError: this.onError
  58707. }, engine);
  58708. if (!this._effect.isReady()) {
  58709. return false;
  58710. }
  58711. if (previousEffect !== this._effect) {
  58712. scene.resetCachedMaterial();
  58713. }
  58714. this._renderId = scene.getRenderId();
  58715. return true;
  58716. };
  58717. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58718. var scene = this.getScene();
  58719. if (!this._effect) {
  58720. return;
  58721. }
  58722. if (this._options.uniforms.indexOf("world") !== -1) {
  58723. this._effect.setMatrix("world", world);
  58724. }
  58725. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58726. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58727. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58728. }
  58729. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58730. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58731. }
  58732. };
  58733. ShaderMaterial.prototype.bind = function (world, mesh) {
  58734. // Std values
  58735. this.bindOnlyWorldMatrix(world);
  58736. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58737. if (this._options.uniforms.indexOf("view") !== -1) {
  58738. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58739. }
  58740. if (this._options.uniforms.indexOf("projection") !== -1) {
  58741. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58742. }
  58743. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58744. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58745. }
  58746. // Bones
  58747. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58748. var name;
  58749. // Texture
  58750. for (name in this._textures) {
  58751. this._effect.setTexture(name, this._textures[name]);
  58752. }
  58753. // Texture arrays
  58754. for (name in this._textureArrays) {
  58755. this._effect.setTextureArray(name, this._textureArrays[name]);
  58756. }
  58757. // Int
  58758. for (name in this._ints) {
  58759. this._effect.setInt(name, this._ints[name]);
  58760. }
  58761. // Float
  58762. for (name in this._floats) {
  58763. this._effect.setFloat(name, this._floats[name]);
  58764. }
  58765. // Floats
  58766. for (name in this._floatsArrays) {
  58767. this._effect.setArray(name, this._floatsArrays[name]);
  58768. }
  58769. // Color3
  58770. for (name in this._colors3) {
  58771. this._effect.setColor3(name, this._colors3[name]);
  58772. }
  58773. for (name in this._colors3Arrays) {
  58774. this._effect.setArray3(name, this._colors3Arrays[name]);
  58775. }
  58776. // Color4
  58777. for (name in this._colors4) {
  58778. var color = this._colors4[name];
  58779. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58780. }
  58781. // Vector2
  58782. for (name in this._vectors2) {
  58783. this._effect.setVector2(name, this._vectors2[name]);
  58784. }
  58785. // Vector3
  58786. for (name in this._vectors3) {
  58787. this._effect.setVector3(name, this._vectors3[name]);
  58788. }
  58789. // Vector4
  58790. for (name in this._vectors4) {
  58791. this._effect.setVector4(name, this._vectors4[name]);
  58792. }
  58793. // Matrix
  58794. for (name in this._matrices) {
  58795. this._effect.setMatrix(name, this._matrices[name]);
  58796. }
  58797. // Matrix 3x3
  58798. for (name in this._matrices3x3) {
  58799. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58800. }
  58801. // Matrix 2x2
  58802. for (name in this._matrices2x2) {
  58803. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58804. }
  58805. // Vector2Array
  58806. for (name in this._vectors2Arrays) {
  58807. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58808. }
  58809. // Vector3Array
  58810. for (name in this._vectors3Arrays) {
  58811. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58812. }
  58813. }
  58814. this._afterBind(mesh);
  58815. };
  58816. ShaderMaterial.prototype.getActiveTextures = function () {
  58817. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58818. for (var name in this._textures) {
  58819. activeTextures.push(this._textures[name]);
  58820. }
  58821. for (var name in this._textureArrays) {
  58822. var array = this._textureArrays[name];
  58823. for (var index = 0; index < array.length; index++) {
  58824. activeTextures.push(array[index]);
  58825. }
  58826. }
  58827. return activeTextures;
  58828. };
  58829. ShaderMaterial.prototype.hasTexture = function (texture) {
  58830. if (_super.prototype.hasTexture.call(this, texture)) {
  58831. return true;
  58832. }
  58833. for (var name in this._textures) {
  58834. if (this._textures[name] === texture) {
  58835. return true;
  58836. }
  58837. }
  58838. for (var name in this._textureArrays) {
  58839. var array = this._textureArrays[name];
  58840. for (var index = 0; index < array.length; index++) {
  58841. if (array[index] === texture) {
  58842. return true;
  58843. }
  58844. }
  58845. }
  58846. return false;
  58847. };
  58848. ShaderMaterial.prototype.clone = function (name) {
  58849. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58850. return newShaderMaterial;
  58851. };
  58852. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58853. if (forceDisposeTextures) {
  58854. var name;
  58855. for (name in this._textures) {
  58856. this._textures[name].dispose();
  58857. }
  58858. for (name in this._textureArrays) {
  58859. var array = this._textureArrays[name];
  58860. for (var index = 0; index < array.length; index++) {
  58861. array[index].dispose();
  58862. }
  58863. }
  58864. }
  58865. this._textures = {};
  58866. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58867. };
  58868. ShaderMaterial.prototype.serialize = function () {
  58869. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58870. serializationObject.customType = "BABYLON.ShaderMaterial";
  58871. serializationObject.options = this._options;
  58872. serializationObject.shaderPath = this._shaderPath;
  58873. var name;
  58874. // Texture
  58875. serializationObject.textures = {};
  58876. for (name in this._textures) {
  58877. serializationObject.textures[name] = this._textures[name].serialize();
  58878. }
  58879. // Texture arrays
  58880. serializationObject.textureArrays = {};
  58881. for (name in this._textureArrays) {
  58882. serializationObject.textureArrays[name] = [];
  58883. var array = this._textureArrays[name];
  58884. for (var index = 0; index < array.length; index++) {
  58885. serializationObject.textureArrays[name].push(array[index].serialize());
  58886. }
  58887. }
  58888. // Float
  58889. serializationObject.floats = {};
  58890. for (name in this._floats) {
  58891. serializationObject.floats[name] = this._floats[name];
  58892. }
  58893. // Float s
  58894. serializationObject.FloatArrays = {};
  58895. for (name in this._floatsArrays) {
  58896. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58897. }
  58898. // Color3
  58899. serializationObject.colors3 = {};
  58900. for (name in this._colors3) {
  58901. serializationObject.colors3[name] = this._colors3[name].asArray();
  58902. }
  58903. // Color3 array
  58904. serializationObject.colors3Arrays = {};
  58905. for (name in this._colors3Arrays) {
  58906. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58907. }
  58908. // Color4
  58909. serializationObject.colors4 = {};
  58910. for (name in this._colors4) {
  58911. serializationObject.colors4[name] = this._colors4[name].asArray();
  58912. }
  58913. // Vector2
  58914. serializationObject.vectors2 = {};
  58915. for (name in this._vectors2) {
  58916. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58917. }
  58918. // Vector3
  58919. serializationObject.vectors3 = {};
  58920. for (name in this._vectors3) {
  58921. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58922. }
  58923. // Vector4
  58924. serializationObject.vectors4 = {};
  58925. for (name in this._vectors4) {
  58926. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58927. }
  58928. // Matrix
  58929. serializationObject.matrices = {};
  58930. for (name in this._matrices) {
  58931. serializationObject.matrices[name] = this._matrices[name].asArray();
  58932. }
  58933. // Matrix 3x3
  58934. serializationObject.matrices3x3 = {};
  58935. for (name in this._matrices3x3) {
  58936. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58937. }
  58938. // Matrix 2x2
  58939. serializationObject.matrices2x2 = {};
  58940. for (name in this._matrices2x2) {
  58941. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58942. }
  58943. // Vector2Array
  58944. serializationObject.vectors2Arrays = {};
  58945. for (name in this._vectors2Arrays) {
  58946. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58947. }
  58948. // Vector3Array
  58949. serializationObject.vectors3Arrays = {};
  58950. for (name in this._vectors3Arrays) {
  58951. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58952. }
  58953. return serializationObject;
  58954. };
  58955. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58956. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58957. var name;
  58958. // Texture
  58959. for (name in source.textures) {
  58960. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58961. }
  58962. // Texture arrays
  58963. for (name in source.textureArrays) {
  58964. var array = source.textureArrays[name];
  58965. var textureArray = new Array();
  58966. for (var index = 0; index < array.length; index++) {
  58967. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58968. }
  58969. material.setTextureArray(name, textureArray);
  58970. }
  58971. // Float
  58972. for (name in source.floats) {
  58973. material.setFloat(name, source.floats[name]);
  58974. }
  58975. // Float s
  58976. for (name in source.floatsArrays) {
  58977. material.setFloats(name, source.floatsArrays[name]);
  58978. }
  58979. // Color3
  58980. for (name in source.colors3) {
  58981. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58982. }
  58983. // Color3 arrays
  58984. for (name in source.colors3Arrays) {
  58985. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58986. if (i % 3 === 0) {
  58987. arr.push([num]);
  58988. }
  58989. else {
  58990. arr[arr.length - 1].push(num);
  58991. }
  58992. return arr;
  58993. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58994. material.setColor3Array(name, colors);
  58995. }
  58996. // Color4
  58997. for (name in source.colors4) {
  58998. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58999. }
  59000. // Vector2
  59001. for (name in source.vectors2) {
  59002. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59003. }
  59004. // Vector3
  59005. for (name in source.vectors3) {
  59006. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59007. }
  59008. // Vector4
  59009. for (name in source.vectors4) {
  59010. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59011. }
  59012. // Matrix
  59013. for (name in source.matrices) {
  59014. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59015. }
  59016. // Matrix 3x3
  59017. for (name in source.matrices3x3) {
  59018. material.setMatrix3x3(name, source.matrices3x3[name]);
  59019. }
  59020. // Matrix 2x2
  59021. for (name in source.matrices2x2) {
  59022. material.setMatrix2x2(name, source.matrices2x2[name]);
  59023. }
  59024. // Vector2Array
  59025. for (name in source.vectors2Arrays) {
  59026. material.setArray2(name, source.vectors2Arrays[name]);
  59027. }
  59028. // Vector3Array
  59029. for (name in source.vectors3Arrays) {
  59030. material.setArray3(name, source.vectors3Arrays[name]);
  59031. }
  59032. return material;
  59033. };
  59034. return ShaderMaterial;
  59035. }(BABYLON.Material));
  59036. BABYLON.ShaderMaterial = ShaderMaterial;
  59037. })(BABYLON || (BABYLON = {}));
  59038. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59039. var BABYLON;
  59040. (function (BABYLON) {
  59041. var GroundMesh = /** @class */ (function (_super) {
  59042. __extends(GroundMesh, _super);
  59043. function GroundMesh(name, scene) {
  59044. var _this = _super.call(this, name, scene) || this;
  59045. _this.generateOctree = false;
  59046. return _this;
  59047. }
  59048. GroundMesh.prototype.getClassName = function () {
  59049. return "GroundMesh";
  59050. };
  59051. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59052. get: function () {
  59053. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59054. },
  59055. enumerable: true,
  59056. configurable: true
  59057. });
  59058. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59059. get: function () {
  59060. return this._subdivisionsX;
  59061. },
  59062. enumerable: true,
  59063. configurable: true
  59064. });
  59065. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59066. get: function () {
  59067. return this._subdivisionsY;
  59068. },
  59069. enumerable: true,
  59070. configurable: true
  59071. });
  59072. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59073. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59074. this._subdivisionsX = chunksCount;
  59075. this._subdivisionsY = chunksCount;
  59076. this.subdivide(chunksCount);
  59077. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59078. };
  59079. /**
  59080. * Returns a height (y) value in the Worl system :
  59081. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59082. * Returns the ground y position if (x, z) are outside the ground surface.
  59083. */
  59084. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59085. var world = this.getWorldMatrix();
  59086. var invMat = BABYLON.Tmp.Matrix[5];
  59087. world.invertToRef(invMat);
  59088. var tmpVect = BABYLON.Tmp.Vector3[8];
  59089. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59090. x = tmpVect.x;
  59091. z = tmpVect.z;
  59092. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59093. return this.position.y;
  59094. }
  59095. if (!this._heightQuads || this._heightQuads.length == 0) {
  59096. this._initHeightQuads();
  59097. this._computeHeightQuads();
  59098. }
  59099. var facet = this._getFacetAt(x, z);
  59100. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59101. // return y in the World system
  59102. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59103. return tmpVect.y;
  59104. };
  59105. /**
  59106. * Returns a normalized vector (Vector3) orthogonal to the ground
  59107. * at the ground coordinates (x, z) expressed in the World system.
  59108. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59109. */
  59110. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59111. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59112. this.getNormalAtCoordinatesToRef(x, z, normal);
  59113. return normal;
  59114. };
  59115. /**
  59116. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59117. * at the ground coordinates (x, z) expressed in the World system.
  59118. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59119. * Returns the GroundMesh.
  59120. */
  59121. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59122. var world = this.getWorldMatrix();
  59123. var tmpMat = BABYLON.Tmp.Matrix[5];
  59124. world.invertToRef(tmpMat);
  59125. var tmpVect = BABYLON.Tmp.Vector3[8];
  59126. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59127. x = tmpVect.x;
  59128. z = tmpVect.z;
  59129. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59130. return this;
  59131. }
  59132. if (!this._heightQuads || this._heightQuads.length == 0) {
  59133. this._initHeightQuads();
  59134. this._computeHeightQuads();
  59135. }
  59136. var facet = this._getFacetAt(x, z);
  59137. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59138. return this;
  59139. };
  59140. /**
  59141. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59142. * if the ground has been updated.
  59143. * This can be used in the render loop.
  59144. * Returns the GroundMesh.
  59145. */
  59146. GroundMesh.prototype.updateCoordinateHeights = function () {
  59147. if (!this._heightQuads || this._heightQuads.length == 0) {
  59148. this._initHeightQuads();
  59149. }
  59150. this._computeHeightQuads();
  59151. return this;
  59152. };
  59153. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59154. GroundMesh.prototype._getFacetAt = function (x, z) {
  59155. // retrieve col and row from x, z coordinates in the ground local system
  59156. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59157. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59158. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59159. var facet;
  59160. if (z < quad.slope.x * x + quad.slope.y) {
  59161. facet = quad.facet1;
  59162. }
  59163. else {
  59164. facet = quad.facet2;
  59165. }
  59166. return facet;
  59167. };
  59168. // Creates and populates the heightMap array with "facet" elements :
  59169. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59170. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59171. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59172. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59173. // Returns the GroundMesh.
  59174. GroundMesh.prototype._initHeightQuads = function () {
  59175. var subdivisionsX = this._subdivisionsX;
  59176. var subdivisionsY = this._subdivisionsY;
  59177. this._heightQuads = new Array();
  59178. for (var row = 0; row < subdivisionsY; row++) {
  59179. for (var col = 0; col < subdivisionsX; col++) {
  59180. 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) };
  59181. this._heightQuads[row * subdivisionsX + col] = quad;
  59182. }
  59183. }
  59184. return this;
  59185. };
  59186. // Compute each quad element values and update the the heightMap array :
  59187. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59188. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59189. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59190. // Returns the GroundMesh.
  59191. GroundMesh.prototype._computeHeightQuads = function () {
  59192. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59193. if (!positions) {
  59194. return this;
  59195. }
  59196. var v1 = BABYLON.Tmp.Vector3[3];
  59197. var v2 = BABYLON.Tmp.Vector3[2];
  59198. var v3 = BABYLON.Tmp.Vector3[1];
  59199. var v4 = BABYLON.Tmp.Vector3[0];
  59200. var v1v2 = BABYLON.Tmp.Vector3[4];
  59201. var v1v3 = BABYLON.Tmp.Vector3[5];
  59202. var v1v4 = BABYLON.Tmp.Vector3[6];
  59203. var norm1 = BABYLON.Tmp.Vector3[7];
  59204. var norm2 = BABYLON.Tmp.Vector3[8];
  59205. var i = 0;
  59206. var j = 0;
  59207. var k = 0;
  59208. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59209. var h = 0;
  59210. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59211. var d2 = 0;
  59212. var subdivisionsX = this._subdivisionsX;
  59213. var subdivisionsY = this._subdivisionsY;
  59214. for (var row = 0; row < subdivisionsY; row++) {
  59215. for (var col = 0; col < subdivisionsX; col++) {
  59216. i = col * 3;
  59217. j = row * (subdivisionsX + 1) * 3;
  59218. k = (row + 1) * (subdivisionsX + 1) * 3;
  59219. v1.x = positions[j + i];
  59220. v1.y = positions[j + i + 1];
  59221. v1.z = positions[j + i + 2];
  59222. v2.x = positions[j + i + 3];
  59223. v2.y = positions[j + i + 4];
  59224. v2.z = positions[j + i + 5];
  59225. v3.x = positions[k + i];
  59226. v3.y = positions[k + i + 1];
  59227. v3.z = positions[k + i + 2];
  59228. v4.x = positions[k + i + 3];
  59229. v4.y = positions[k + i + 4];
  59230. v4.z = positions[k + i + 5];
  59231. // 2D slope V1V4
  59232. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59233. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59234. // facet equations :
  59235. // we compute each facet normal vector
  59236. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59237. // we compute the value d by applying the equation to v1 which belongs to the plane
  59238. // then we store the facet equation in a Vector4
  59239. v2.subtractToRef(v1, v1v2);
  59240. v3.subtractToRef(v1, v1v3);
  59241. v4.subtractToRef(v1, v1v4);
  59242. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59243. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59244. norm1.normalize();
  59245. norm2.normalize();
  59246. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59247. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59248. var quad = this._heightQuads[row * subdivisionsX + col];
  59249. quad.slope.copyFromFloats(cd, h);
  59250. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59251. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59252. }
  59253. }
  59254. return this;
  59255. };
  59256. GroundMesh.prototype.serialize = function (serializationObject) {
  59257. _super.prototype.serialize.call(this, serializationObject);
  59258. serializationObject.subdivisionsX = this._subdivisionsX;
  59259. serializationObject.subdivisionsY = this._subdivisionsY;
  59260. serializationObject.minX = this._minX;
  59261. serializationObject.maxX = this._maxX;
  59262. serializationObject.minZ = this._minZ;
  59263. serializationObject.maxZ = this._maxZ;
  59264. serializationObject.width = this._width;
  59265. serializationObject.height = this._height;
  59266. };
  59267. GroundMesh.Parse = function (parsedMesh, scene) {
  59268. var result = new GroundMesh(parsedMesh.name, scene);
  59269. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59270. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59271. result._minX = parsedMesh.minX;
  59272. result._maxX = parsedMesh.maxX;
  59273. result._minZ = parsedMesh.minZ;
  59274. result._maxZ = parsedMesh.maxZ;
  59275. result._width = parsedMesh.width;
  59276. result._height = parsedMesh.height;
  59277. return result;
  59278. };
  59279. return GroundMesh;
  59280. }(BABYLON.Mesh));
  59281. BABYLON.GroundMesh = GroundMesh;
  59282. })(BABYLON || (BABYLON = {}));
  59283. //# sourceMappingURL=babylon.groundMesh.js.map
  59284. var BABYLON;
  59285. (function (BABYLON) {
  59286. /**
  59287. * Creates an instance based on a source mesh.
  59288. */
  59289. var InstancedMesh = /** @class */ (function (_super) {
  59290. __extends(InstancedMesh, _super);
  59291. function InstancedMesh(name, source) {
  59292. var _this = _super.call(this, name, source.getScene()) || this;
  59293. source.instances.push(_this);
  59294. _this._sourceMesh = source;
  59295. _this.position.copyFrom(source.position);
  59296. _this.rotation.copyFrom(source.rotation);
  59297. _this.scaling.copyFrom(source.scaling);
  59298. if (source.rotationQuaternion) {
  59299. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59300. }
  59301. _this.infiniteDistance = source.infiniteDistance;
  59302. _this.setPivotMatrix(source.getPivotMatrix());
  59303. _this.refreshBoundingInfo();
  59304. _this._syncSubMeshes();
  59305. return _this;
  59306. }
  59307. /**
  59308. * Returns the string "InstancedMesh".
  59309. */
  59310. InstancedMesh.prototype.getClassName = function () {
  59311. return "InstancedMesh";
  59312. };
  59313. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59314. // Methods
  59315. get: function () {
  59316. return this._sourceMesh.receiveShadows;
  59317. },
  59318. enumerable: true,
  59319. configurable: true
  59320. });
  59321. Object.defineProperty(InstancedMesh.prototype, "material", {
  59322. get: function () {
  59323. return this._sourceMesh.material;
  59324. },
  59325. enumerable: true,
  59326. configurable: true
  59327. });
  59328. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59329. get: function () {
  59330. return this._sourceMesh.visibility;
  59331. },
  59332. enumerable: true,
  59333. configurable: true
  59334. });
  59335. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59336. get: function () {
  59337. return this._sourceMesh.skeleton;
  59338. },
  59339. enumerable: true,
  59340. configurable: true
  59341. });
  59342. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59343. get: function () {
  59344. return this._sourceMesh.renderingGroupId;
  59345. },
  59346. set: function (value) {
  59347. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59348. return;
  59349. }
  59350. //no-op with warning
  59351. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59352. },
  59353. enumerable: true,
  59354. configurable: true
  59355. });
  59356. /**
  59357. * Returns the total number of vertices (integer).
  59358. */
  59359. InstancedMesh.prototype.getTotalVertices = function () {
  59360. return this._sourceMesh.getTotalVertices();
  59361. };
  59362. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59363. get: function () {
  59364. return this._sourceMesh;
  59365. },
  59366. enumerable: true,
  59367. configurable: true
  59368. });
  59369. /**
  59370. * Is this node ready to be used/rendered
  59371. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59372. * @return {boolean} is it ready
  59373. */
  59374. InstancedMesh.prototype.isReady = function (completeCheck) {
  59375. if (completeCheck === void 0) { completeCheck = false; }
  59376. return this._sourceMesh.isReady(completeCheck, true);
  59377. };
  59378. /**
  59379. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59380. */
  59381. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59382. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59383. };
  59384. /**
  59385. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59386. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59387. * The `data` are either a numeric array either a Float32Array.
  59388. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59389. * 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).
  59390. * Note that a new underlying VertexBuffer object is created each call.
  59391. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59392. *
  59393. * Possible `kind` values :
  59394. * - BABYLON.VertexBuffer.PositionKind
  59395. * - BABYLON.VertexBuffer.UVKind
  59396. * - BABYLON.VertexBuffer.UV2Kind
  59397. * - BABYLON.VertexBuffer.UV3Kind
  59398. * - BABYLON.VertexBuffer.UV4Kind
  59399. * - BABYLON.VertexBuffer.UV5Kind
  59400. * - BABYLON.VertexBuffer.UV6Kind
  59401. * - BABYLON.VertexBuffer.ColorKind
  59402. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59403. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59404. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59405. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59406. *
  59407. * Returns the Mesh.
  59408. */
  59409. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59410. if (this.sourceMesh) {
  59411. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59412. }
  59413. return this.sourceMesh;
  59414. };
  59415. /**
  59416. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59417. * If the mesh has no geometry, it is simply returned as it is.
  59418. * The `data` are either a numeric array either a Float32Array.
  59419. * No new underlying VertexBuffer object is created.
  59420. * 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.
  59421. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59422. *
  59423. * Possible `kind` values :
  59424. * - BABYLON.VertexBuffer.PositionKind
  59425. * - BABYLON.VertexBuffer.UVKind
  59426. * - BABYLON.VertexBuffer.UV2Kind
  59427. * - BABYLON.VertexBuffer.UV3Kind
  59428. * - BABYLON.VertexBuffer.UV4Kind
  59429. * - BABYLON.VertexBuffer.UV5Kind
  59430. * - BABYLON.VertexBuffer.UV6Kind
  59431. * - BABYLON.VertexBuffer.ColorKind
  59432. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59433. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59434. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59435. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59436. *
  59437. * Returns the Mesh.
  59438. */
  59439. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59440. if (this.sourceMesh) {
  59441. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59442. }
  59443. return this.sourceMesh;
  59444. };
  59445. /**
  59446. * Sets the mesh indices.
  59447. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59448. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59449. * This method creates a new index buffer each call.
  59450. * Returns the Mesh.
  59451. */
  59452. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59453. if (totalVertices === void 0) { totalVertices = null; }
  59454. if (this.sourceMesh) {
  59455. this.sourceMesh.setIndices(indices, totalVertices);
  59456. }
  59457. return this.sourceMesh;
  59458. };
  59459. /**
  59460. * Boolean : True if the mesh owns the requested kind of data.
  59461. */
  59462. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59463. return this._sourceMesh.isVerticesDataPresent(kind);
  59464. };
  59465. /**
  59466. * Returns an array of indices (IndicesArray).
  59467. */
  59468. InstancedMesh.prototype.getIndices = function () {
  59469. return this._sourceMesh.getIndices();
  59470. };
  59471. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59472. get: function () {
  59473. return this._sourceMesh._positions;
  59474. },
  59475. enumerable: true,
  59476. configurable: true
  59477. });
  59478. /**
  59479. * Sets a new updated BoundingInfo to the mesh.
  59480. * Returns the mesh.
  59481. */
  59482. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59483. var meshBB = this._sourceMesh.getBoundingInfo();
  59484. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59485. this._updateBoundingInfo();
  59486. return this;
  59487. };
  59488. InstancedMesh.prototype._preActivate = function () {
  59489. if (this._currentLOD) {
  59490. this._currentLOD._preActivate();
  59491. }
  59492. return this;
  59493. };
  59494. InstancedMesh.prototype._activate = function (renderId) {
  59495. if (this._currentLOD) {
  59496. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59497. }
  59498. return this;
  59499. };
  59500. /**
  59501. * Returns the current associated LOD AbstractMesh.
  59502. */
  59503. InstancedMesh.prototype.getLOD = function (camera) {
  59504. if (!camera) {
  59505. return this;
  59506. }
  59507. var boundingInfo = this.getBoundingInfo();
  59508. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59509. if (this._currentLOD === this.sourceMesh) {
  59510. return this;
  59511. }
  59512. return this._currentLOD;
  59513. };
  59514. InstancedMesh.prototype._syncSubMeshes = function () {
  59515. this.releaseSubMeshes();
  59516. if (this._sourceMesh.subMeshes) {
  59517. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59518. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59519. }
  59520. }
  59521. return this;
  59522. };
  59523. InstancedMesh.prototype._generatePointsArray = function () {
  59524. return this._sourceMesh._generatePointsArray();
  59525. };
  59526. /**
  59527. * Creates a new InstancedMesh from the current mesh.
  59528. * - name (string) : the cloned mesh name
  59529. * - newParent (optional Node) : the optional Node to parent the clone to.
  59530. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59531. *
  59532. * Returns the clone.
  59533. */
  59534. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59535. var result = this._sourceMesh.createInstance(name);
  59536. // Deep copy
  59537. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59538. // Bounding info
  59539. this.refreshBoundingInfo();
  59540. // Parent
  59541. if (newParent) {
  59542. result.parent = newParent;
  59543. }
  59544. if (!doNotCloneChildren) {
  59545. // Children
  59546. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59547. var mesh = this.getScene().meshes[index];
  59548. if (mesh.parent === this) {
  59549. mesh.clone(mesh.name, result);
  59550. }
  59551. }
  59552. }
  59553. result.computeWorldMatrix(true);
  59554. return result;
  59555. };
  59556. /**
  59557. * Disposes the InstancedMesh.
  59558. * Returns nothing.
  59559. */
  59560. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59561. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59562. // Remove from mesh
  59563. var index = this._sourceMesh.instances.indexOf(this);
  59564. this._sourceMesh.instances.splice(index, 1);
  59565. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59566. };
  59567. return InstancedMesh;
  59568. }(BABYLON.AbstractMesh));
  59569. BABYLON.InstancedMesh = InstancedMesh;
  59570. })(BABYLON || (BABYLON = {}));
  59571. //# sourceMappingURL=babylon.instancedMesh.js.map
  59572. var BABYLON;
  59573. (function (BABYLON) {
  59574. var LinesMesh = /** @class */ (function (_super) {
  59575. __extends(LinesMesh, _super);
  59576. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59577. if (scene === void 0) { scene = null; }
  59578. if (parent === void 0) { parent = null; }
  59579. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59580. _this.useVertexColor = useVertexColor;
  59581. _this.useVertexAlpha = useVertexAlpha;
  59582. _this.color = new BABYLON.Color3(1, 1, 1);
  59583. _this.alpha = 1;
  59584. if (source) {
  59585. _this.color = source.color.clone();
  59586. _this.alpha = source.alpha;
  59587. _this.useVertexColor = source.useVertexColor;
  59588. _this.useVertexAlpha = source.useVertexAlpha;
  59589. }
  59590. _this._intersectionThreshold = 0.1;
  59591. var defines = [];
  59592. var options = {
  59593. attributes: [BABYLON.VertexBuffer.PositionKind],
  59594. uniforms: ["world", "viewProjection"],
  59595. needAlphaBlending: true,
  59596. defines: defines
  59597. };
  59598. if (useVertexAlpha === false) {
  59599. options.needAlphaBlending = false;
  59600. }
  59601. if (!useVertexColor) {
  59602. options.uniforms.push("color");
  59603. }
  59604. else {
  59605. options.defines.push("#define VERTEXCOLOR");
  59606. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59607. }
  59608. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59609. return _this;
  59610. }
  59611. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59612. /**
  59613. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59614. * This margin is expressed in world space coordinates, so its value may vary.
  59615. * Default value is 0.1
  59616. * @returns the intersection Threshold value.
  59617. */
  59618. get: function () {
  59619. return this._intersectionThreshold;
  59620. },
  59621. /**
  59622. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59623. * This margin is expressed in world space coordinates, so its value may vary.
  59624. * @param value the new threshold to apply
  59625. */
  59626. set: function (value) {
  59627. if (this._intersectionThreshold === value) {
  59628. return;
  59629. }
  59630. this._intersectionThreshold = value;
  59631. if (this.geometry) {
  59632. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59633. }
  59634. },
  59635. enumerable: true,
  59636. configurable: true
  59637. });
  59638. /**
  59639. * Returns the string "LineMesh"
  59640. */
  59641. LinesMesh.prototype.getClassName = function () {
  59642. return "LinesMesh";
  59643. };
  59644. Object.defineProperty(LinesMesh.prototype, "material", {
  59645. get: function () {
  59646. return this._colorShader;
  59647. },
  59648. set: function (value) {
  59649. // Do nothing
  59650. },
  59651. enumerable: true,
  59652. configurable: true
  59653. });
  59654. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59655. get: function () {
  59656. return false;
  59657. },
  59658. enumerable: true,
  59659. configurable: true
  59660. });
  59661. LinesMesh.prototype.createInstance = function (name) {
  59662. throw new Error("LinesMeshes do not support createInstance.");
  59663. };
  59664. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59665. if (!this._geometry) {
  59666. return this;
  59667. }
  59668. // VBOs
  59669. this._geometry._bind(this._colorShader.getEffect());
  59670. // Color
  59671. if (!this.useVertexColor) {
  59672. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59673. }
  59674. return this;
  59675. };
  59676. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59677. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59678. return this;
  59679. }
  59680. var engine = this.getScene().getEngine();
  59681. // Draw order
  59682. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59683. return this;
  59684. };
  59685. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59686. this._colorShader.dispose();
  59687. _super.prototype.dispose.call(this, doNotRecurse);
  59688. };
  59689. /**
  59690. * Returns a new LineMesh object cloned from the current one.
  59691. */
  59692. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59693. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59694. };
  59695. return LinesMesh;
  59696. }(BABYLON.Mesh));
  59697. BABYLON.LinesMesh = LinesMesh;
  59698. })(BABYLON || (BABYLON = {}));
  59699. //# sourceMappingURL=babylon.linesMesh.js.map
  59700. var BABYLON;
  59701. (function (BABYLON) {
  59702. /**
  59703. * Class containing static functions to help procedurally build meshes
  59704. */
  59705. var MeshBuilder = /** @class */ (function () {
  59706. function MeshBuilder() {
  59707. }
  59708. MeshBuilder.updateSideOrientation = function (orientation) {
  59709. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59710. return BABYLON.Mesh.DOUBLESIDE;
  59711. }
  59712. if (orientation === undefined || orientation === null) {
  59713. return BABYLON.Mesh.FRONTSIDE;
  59714. }
  59715. return orientation;
  59716. };
  59717. /**
  59718. * Creates a box mesh
  59719. * * The parameter `size` sets the size (float) of each box side (default 1)
  59720. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59721. * * 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)
  59722. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59723. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59724. * * 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
  59725. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59726. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59727. * @param name defines the name of the mesh
  59728. * @param options defines the options used to create the mesh
  59729. * @param scene defines the hosting scene
  59730. * @returns the box mesh
  59731. */
  59732. MeshBuilder.CreateBox = function (name, options, scene) {
  59733. if (scene === void 0) { scene = null; }
  59734. var box = new BABYLON.Mesh(name, scene);
  59735. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59736. box._originalBuilderSideOrientation = options.sideOrientation;
  59737. var vertexData = BABYLON.VertexData.CreateBox(options);
  59738. vertexData.applyToMesh(box, options.updatable);
  59739. return box;
  59740. };
  59741. /**
  59742. * Creates a sphere mesh
  59743. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59744. * * 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`)
  59745. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59746. * * 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
  59747. * * 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)
  59748. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59749. * * 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
  59750. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59751. * @param name defines the name of the mesh
  59752. * @param options defines the options used to create the mesh
  59753. * @param scene defines the hosting scene
  59754. * @returns the sphere mesh
  59755. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59756. */
  59757. MeshBuilder.CreateSphere = function (name, options, scene) {
  59758. var sphere = new BABYLON.Mesh(name, scene);
  59759. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59760. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59761. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59762. vertexData.applyToMesh(sphere, options.updatable);
  59763. return sphere;
  59764. };
  59765. /**
  59766. * Creates a plane polygonal mesh. By default, this is a disc
  59767. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59768. * * 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
  59769. * * 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
  59770. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59771. * * 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
  59772. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59773. * @param name defines the name of the mesh
  59774. * @param options defines the options used to create the mesh
  59775. * @param scene defines the hosting scene
  59776. * @returns the plane polygonal mesh
  59777. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  59778. */
  59779. MeshBuilder.CreateDisc = function (name, options, scene) {
  59780. if (scene === void 0) { scene = null; }
  59781. var disc = new BABYLON.Mesh(name, scene);
  59782. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59783. disc._originalBuilderSideOrientation = options.sideOrientation;
  59784. var vertexData = BABYLON.VertexData.CreateDisc(options);
  59785. vertexData.applyToMesh(disc, options.updatable);
  59786. return disc;
  59787. };
  59788. /**
  59789. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  59790. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  59791. * * 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`)
  59792. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  59793. * * 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
  59794. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59795. * * 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
  59796. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59797. * @param name defines the name of the mesh
  59798. * @param options defines the options used to create the mesh
  59799. * @param scene defines the hosting scene
  59800. * @returns the icosahedron mesh
  59801. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  59802. */
  59803. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  59804. var sphere = new BABYLON.Mesh(name, scene);
  59805. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59806. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59807. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  59808. vertexData.applyToMesh(sphere, options.updatable);
  59809. return sphere;
  59810. };
  59811. ;
  59812. /**
  59813. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59814. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  59815. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  59816. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  59817. * * 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
  59818. * * 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
  59819. * * 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
  59820. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59821. * * 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
  59822. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59823. * * 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
  59824. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  59825. * * 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
  59826. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  59827. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59828. * @param name defines the name of the mesh
  59829. * @param options defines the options used to create the mesh
  59830. * @param scene defines the hosting scene
  59831. * @returns the ribbon mesh
  59832. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  59833. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59834. */
  59835. MeshBuilder.CreateRibbon = function (name, options, scene) {
  59836. if (scene === void 0) { scene = null; }
  59837. var pathArray = options.pathArray;
  59838. var closeArray = options.closeArray;
  59839. var closePath = options.closePath;
  59840. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59841. var instance = options.instance;
  59842. var updatable = options.updatable;
  59843. if (instance) { // existing ribbon instance update
  59844. // positionFunction : ribbon case
  59845. // only pathArray and sideOrientation parameters are taken into account for positions update
  59846. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  59847. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  59848. var positionFunction = function (positions) {
  59849. var minlg = pathArray[0].length;
  59850. var i = 0;
  59851. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  59852. for (var si = 1; si <= ns; si++) {
  59853. for (var p = 0; p < pathArray.length; p++) {
  59854. var path = pathArray[p];
  59855. var l = path.length;
  59856. minlg = (minlg < l) ? minlg : l;
  59857. var j = 0;
  59858. while (j < minlg) {
  59859. positions[i] = path[j].x;
  59860. positions[i + 1] = path[j].y;
  59861. positions[i + 2] = path[j].z;
  59862. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  59863. BABYLON.Tmp.Vector3[0].x = path[j].x;
  59864. }
  59865. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  59866. BABYLON.Tmp.Vector3[1].x = path[j].x;
  59867. }
  59868. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  59869. BABYLON.Tmp.Vector3[0].y = path[j].y;
  59870. }
  59871. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  59872. BABYLON.Tmp.Vector3[1].y = path[j].y;
  59873. }
  59874. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  59875. BABYLON.Tmp.Vector3[0].z = path[j].z;
  59876. }
  59877. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  59878. BABYLON.Tmp.Vector3[1].z = path[j].z;
  59879. }
  59880. j++;
  59881. i += 3;
  59882. }
  59883. if (instance._closePath) {
  59884. positions[i] = path[0].x;
  59885. positions[i + 1] = path[0].y;
  59886. positions[i + 2] = path[0].z;
  59887. i += 3;
  59888. }
  59889. }
  59890. }
  59891. };
  59892. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59893. positionFunction(positions);
  59894. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  59895. instance._boundingInfo.update(instance._worldMatrix);
  59896. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59897. if (options.colors) {
  59898. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59899. for (var c = 0; c < options.colors.length; c++) {
  59900. colors[c * 4] = options.colors[c].r;
  59901. colors[c * 4 + 1] = options.colors[c].g;
  59902. colors[c * 4 + 2] = options.colors[c].b;
  59903. colors[c * 4 + 3] = options.colors[c].a;
  59904. }
  59905. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  59906. }
  59907. if (options.uvs) {
  59908. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59909. for (var i = 0; i < options.uvs.length; i++) {
  59910. uvs[i * 2] = options.uvs[i].x;
  59911. uvs[i * 2 + 1] = options.uvs[i].y;
  59912. }
  59913. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  59914. }
  59915. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  59916. var indices = instance.getIndices();
  59917. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59918. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  59919. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  59920. if (instance._closePath) {
  59921. var indexFirst = 0;
  59922. var indexLast = 0;
  59923. for (var p = 0; p < pathArray.length; p++) {
  59924. indexFirst = instance._idx[p] * 3;
  59925. if (p + 1 < pathArray.length) {
  59926. indexLast = (instance._idx[p + 1] - 1) * 3;
  59927. }
  59928. else {
  59929. indexLast = normals.length - 3;
  59930. }
  59931. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  59932. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  59933. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  59934. normals[indexLast] = normals[indexFirst];
  59935. normals[indexLast + 1] = normals[indexFirst + 1];
  59936. normals[indexLast + 2] = normals[indexFirst + 2];
  59937. }
  59938. }
  59939. if (!(instance.areNormalsFrozen)) {
  59940. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  59941. }
  59942. }
  59943. return instance;
  59944. }
  59945. else { // new ribbon creation
  59946. var ribbon = new BABYLON.Mesh(name, scene);
  59947. ribbon._originalBuilderSideOrientation = sideOrientation;
  59948. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  59949. if (closePath) {
  59950. ribbon._idx = vertexData._idx;
  59951. }
  59952. ribbon._closePath = closePath;
  59953. ribbon._closeArray = closeArray;
  59954. vertexData.applyToMesh(ribbon, updatable);
  59955. return ribbon;
  59956. }
  59957. };
  59958. /**
  59959. * Creates a cylinder or a cone mesh
  59960. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  59961. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  59962. * * 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.
  59963. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  59964. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  59965. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  59966. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  59967. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  59968. * * 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).
  59969. * * 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
  59970. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  59971. * * 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
  59972. * * 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.
  59973. * * If `enclose` is false, a ring surface is one element.
  59974. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  59975. * * 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
  59976. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59977. * * 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
  59978. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59979. * @param name defines the name of the mesh
  59980. * @param options defines the options used to create the mesh
  59981. * @param scene defines the hosting scene
  59982. * @returns the cylinder mesh
  59983. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  59984. */
  59985. MeshBuilder.CreateCylinder = function (name, options, scene) {
  59986. var cylinder = new BABYLON.Mesh(name, scene);
  59987. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59988. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  59989. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  59990. vertexData.applyToMesh(cylinder, options.updatable);
  59991. return cylinder;
  59992. };
  59993. /**
  59994. * Creates a torus mesh
  59995. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  59996. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  59997. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  59998. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59999. * * 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
  60000. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60001. * @param name defines the name of the mesh
  60002. * @param options defines the options used to create the mesh
  60003. * @param scene defines the hosting scene
  60004. * @returns the torus mesh
  60005. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60006. */
  60007. MeshBuilder.CreateTorus = function (name, options, scene) {
  60008. var torus = new BABYLON.Mesh(name, scene);
  60009. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60010. torus._originalBuilderSideOrientation = options.sideOrientation;
  60011. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60012. vertexData.applyToMesh(torus, options.updatable);
  60013. return torus;
  60014. };
  60015. /**
  60016. * Creates a torus knot mesh
  60017. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60018. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60019. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60020. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60021. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60022. * * 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
  60023. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60024. * @param name defines the name of the mesh
  60025. * @param options defines the options used to create the mesh
  60026. * @param scene defines the hosting scene
  60027. * @returns the torus knot mesh
  60028. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60029. */
  60030. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60031. var torusKnot = new BABYLON.Mesh(name, scene);
  60032. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60033. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60034. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60035. vertexData.applyToMesh(torusKnot, options.updatable);
  60036. return torusKnot;
  60037. };
  60038. /**
  60039. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60040. * * 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
  60041. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60042. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60043. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60044. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60045. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60046. * * 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
  60047. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60048. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60049. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60050. * @param name defines the name of the new line system
  60051. * @param options defines the options used to create the line system
  60052. * @param scene defines the hosting scene
  60053. * @returns a new line system mesh
  60054. */
  60055. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60056. var instance = options.instance;
  60057. var lines = options.lines;
  60058. var colors = options.colors;
  60059. if (instance) { // lines update
  60060. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60061. var vertexColor;
  60062. var lineColors;
  60063. if (colors) {
  60064. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60065. }
  60066. var i = 0;
  60067. var c = 0;
  60068. for (var l = 0; l < lines.length; l++) {
  60069. var points = lines[l];
  60070. for (var p = 0; p < points.length; p++) {
  60071. positions[i] = points[p].x;
  60072. positions[i + 1] = points[p].y;
  60073. positions[i + 2] = points[p].z;
  60074. if (colors && vertexColor) {
  60075. lineColors = colors[l];
  60076. vertexColor[c] = lineColors[p].r;
  60077. vertexColor[c + 1] = lineColors[p].g;
  60078. vertexColor[c + 2] = lineColors[p].b;
  60079. vertexColor[c + 3] = lineColors[p].a;
  60080. c += 4;
  60081. }
  60082. i += 3;
  60083. }
  60084. }
  60085. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60086. if (colors && vertexColor) {
  60087. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60088. }
  60089. return instance;
  60090. }
  60091. // line system creation
  60092. var useVertexColor = (colors) ? true : false;
  60093. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60094. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60095. vertexData.applyToMesh(lineSystem, options.updatable);
  60096. return lineSystem;
  60097. };
  60098. /**
  60099. * Creates a line mesh
  60100. * 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
  60101. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60102. * * The parameter `points` is an array successive Vector3
  60103. * * 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
  60104. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60105. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60106. * * When updating an instance, remember that only point positions can change, not the number of points
  60107. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60108. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60109. * @param name defines the name of the new line system
  60110. * @param options defines the options used to create the line system
  60111. * @param scene defines the hosting scene
  60112. * @returns a new line mesh
  60113. */
  60114. MeshBuilder.CreateLines = function (name, options, scene) {
  60115. if (scene === void 0) { scene = null; }
  60116. var colors = (options.colors) ? [options.colors] : null;
  60117. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60118. return lines;
  60119. };
  60120. /**
  60121. * Creates a dashed line mesh
  60122. * * 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
  60123. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60124. * * The parameter `points` is an array successive Vector3
  60125. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60126. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60127. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60128. * * 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
  60129. * * When updating an instance, remember that only point positions can change, not the number of points
  60130. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60131. * @param name defines the name of the mesh
  60132. * @param options defines the options used to create the mesh
  60133. * @param scene defines the hosting scene
  60134. * @returns the dashed line mesh
  60135. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60136. */
  60137. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60138. if (scene === void 0) { scene = null; }
  60139. var points = options.points;
  60140. var instance = options.instance;
  60141. var gapSize = options.gapSize || 1;
  60142. var dashSize = options.dashSize || 3;
  60143. if (instance) { // dashed lines update
  60144. var positionFunction = function (positions) {
  60145. var curvect = BABYLON.Vector3.Zero();
  60146. var nbSeg = positions.length / 6;
  60147. var lg = 0;
  60148. var nb = 0;
  60149. var shft = 0;
  60150. var dashshft = 0;
  60151. var curshft = 0;
  60152. var p = 0;
  60153. var i = 0;
  60154. var j = 0;
  60155. for (i = 0; i < points.length - 1; i++) {
  60156. points[i + 1].subtractToRef(points[i], curvect);
  60157. lg += curvect.length();
  60158. }
  60159. shft = lg / nbSeg;
  60160. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60161. for (i = 0; i < points.length - 1; i++) {
  60162. points[i + 1].subtractToRef(points[i], curvect);
  60163. nb = Math.floor(curvect.length() / shft);
  60164. curvect.normalize();
  60165. j = 0;
  60166. while (j < nb && p < positions.length) {
  60167. curshft = shft * j;
  60168. positions[p] = points[i].x + curshft * curvect.x;
  60169. positions[p + 1] = points[i].y + curshft * curvect.y;
  60170. positions[p + 2] = points[i].z + curshft * curvect.z;
  60171. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60172. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60173. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60174. p += 6;
  60175. j++;
  60176. }
  60177. }
  60178. while (p < positions.length) {
  60179. positions[p] = points[i].x;
  60180. positions[p + 1] = points[i].y;
  60181. positions[p + 2] = points[i].z;
  60182. p += 3;
  60183. }
  60184. };
  60185. instance.updateMeshPositions(positionFunction, false);
  60186. return instance;
  60187. }
  60188. // dashed lines creation
  60189. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60190. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60191. vertexData.applyToMesh(dashedLines, options.updatable);
  60192. dashedLines.dashSize = dashSize;
  60193. dashedLines.gapSize = gapSize;
  60194. return dashedLines;
  60195. };
  60196. /**
  60197. * 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.
  60198. * * 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.
  60199. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60200. * * 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.
  60201. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60202. * * 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
  60203. * * 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
  60204. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60205. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60206. * * 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
  60207. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60208. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60209. * @param name defines the name of the mesh
  60210. * @param options defines the options used to create the mesh
  60211. * @param scene defines the hosting scene
  60212. * @returns the extruded shape mesh
  60213. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60214. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60215. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60216. */
  60217. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60218. if (scene === void 0) { scene = null; }
  60219. var path = options.path;
  60220. var shape = options.shape;
  60221. var scale = options.scale || 1;
  60222. var rotation = options.rotation || 0;
  60223. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60224. var updatable = options.updatable;
  60225. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60226. var instance = options.instance || null;
  60227. var invertUV = options.invertUV || false;
  60228. 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);
  60229. };
  60230. /**
  60231. * Creates an custom extruded shape mesh.
  60232. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60233. * * 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.
  60234. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60235. * * 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
  60236. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60237. * * 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
  60238. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60239. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60240. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60241. * * 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
  60242. * * 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
  60243. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60244. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60245. * * 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
  60246. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60247. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60248. * @param name defines the name of the mesh
  60249. * @param options defines the options used to create the mesh
  60250. * @param scene defines the hosting scene
  60251. * @returns the custom extruded shape mesh
  60252. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60253. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60254. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60255. */
  60256. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60257. var path = options.path;
  60258. var shape = options.shape;
  60259. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60260. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60261. var ribbonCloseArray = options.ribbonCloseArray || false;
  60262. var ribbonClosePath = options.ribbonClosePath || false;
  60263. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60264. var updatable = options.updatable;
  60265. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60266. var instance = options.instance;
  60267. var invertUV = options.invertUV || false;
  60268. 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);
  60269. };
  60270. /**
  60271. * Creates lathe mesh.
  60272. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60273. * * 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
  60274. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60275. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60276. * * 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
  60277. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60278. * * 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
  60279. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60280. * * 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
  60281. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60282. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60283. * @param name defines the name of the mesh
  60284. * @param options defines the options used to create the mesh
  60285. * @param scene defines the hosting scene
  60286. * @returns the lathe mesh
  60287. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60288. */
  60289. MeshBuilder.CreateLathe = function (name, options, scene) {
  60290. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60291. var closed = (options.closed === undefined) ? true : options.closed;
  60292. var shape = options.shape;
  60293. var radius = options.radius || 1;
  60294. var tessellation = options.tessellation || 64;
  60295. var updatable = options.updatable;
  60296. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60297. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60298. var pi2 = Math.PI * 2;
  60299. var paths = new Array();
  60300. var invertUV = options.invertUV || false;
  60301. var i = 0;
  60302. var p = 0;
  60303. var step = pi2 / tessellation * arc;
  60304. var rotated;
  60305. var path = new Array();
  60306. for (i = 0; i <= tessellation; i++) {
  60307. var path = [];
  60308. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60309. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60310. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60311. }
  60312. for (p = 0; p < shape.length; p++) {
  60313. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60314. path.push(rotated);
  60315. }
  60316. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60317. 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));
  60318. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60319. }
  60320. paths.push(path);
  60321. }
  60322. // lathe ribbon
  60323. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60324. return lathe;
  60325. };
  60326. /**
  60327. * Creates a plane mesh
  60328. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60329. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60330. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60331. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60332. * * 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
  60333. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60334. * @param name defines the name of the mesh
  60335. * @param options defines the options used to create the mesh
  60336. * @param scene defines the hosting scene
  60337. * @returns the plane mesh
  60338. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60339. */
  60340. MeshBuilder.CreatePlane = function (name, options, scene) {
  60341. var plane = new BABYLON.Mesh(name, scene);
  60342. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60343. plane._originalBuilderSideOrientation = options.sideOrientation;
  60344. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60345. vertexData.applyToMesh(plane, options.updatable);
  60346. if (options.sourcePlane) {
  60347. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60348. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60349. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60350. plane.rotate(vectorProduct, product);
  60351. }
  60352. return plane;
  60353. };
  60354. /**
  60355. * Creates a ground mesh
  60356. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60357. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  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. * @param name defines the name of the mesh
  60360. * @param options defines the options used to create the mesh
  60361. * @param scene defines the hosting scene
  60362. * @returns the ground mesh
  60363. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60364. */
  60365. MeshBuilder.CreateGround = function (name, options, scene) {
  60366. var ground = new BABYLON.GroundMesh(name, scene);
  60367. ground._setReady(false);
  60368. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60369. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60370. ground._width = options.width || 1;
  60371. ground._height = options.height || 1;
  60372. ground._maxX = ground._width / 2;
  60373. ground._maxZ = ground._height / 2;
  60374. ground._minX = -ground._maxX;
  60375. ground._minZ = -ground._maxZ;
  60376. var vertexData = BABYLON.VertexData.CreateGround(options);
  60377. vertexData.applyToMesh(ground, options.updatable);
  60378. ground._setReady(true);
  60379. return ground;
  60380. };
  60381. /**
  60382. * Creates a tiled ground mesh
  60383. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60384. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60385. * * 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
  60386. * * 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
  60387. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60388. * @param name defines the name of the mesh
  60389. * @param options defines the options used to create the mesh
  60390. * @param scene defines the hosting scene
  60391. * @returns the tiled ground mesh
  60392. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60393. */
  60394. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60395. var tiledGround = new BABYLON.Mesh(name, scene);
  60396. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60397. vertexData.applyToMesh(tiledGround, options.updatable);
  60398. return tiledGround;
  60399. };
  60400. /**
  60401. * Creates a ground mesh from a height map
  60402. * * The parameter `url` sets the URL of the height map image resource.
  60403. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60404. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60405. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60406. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60407. * * 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.
  60408. * * 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).
  60409. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60410. * @param name defines the name of the mesh
  60411. * @param url defines the url to the height map
  60412. * @param options defines the options used to create the mesh
  60413. * @param scene defines the hosting scene
  60414. * @returns the ground mesh
  60415. * @see http://doc.babylonjs.com/babylon101/height_map
  60416. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60417. */
  60418. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60419. var width = options.width || 10.0;
  60420. var height = options.height || 10.0;
  60421. var subdivisions = options.subdivisions || 1 | 0;
  60422. var minHeight = options.minHeight || 0.0;
  60423. var maxHeight = options.maxHeight || 1.0;
  60424. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60425. var updatable = options.updatable;
  60426. var onReady = options.onReady;
  60427. var ground = new BABYLON.GroundMesh(name, scene);
  60428. ground._subdivisionsX = subdivisions;
  60429. ground._subdivisionsY = subdivisions;
  60430. ground._width = width;
  60431. ground._height = height;
  60432. ground._maxX = ground._width / 2.0;
  60433. ground._maxZ = ground._height / 2.0;
  60434. ground._minX = -ground._maxX;
  60435. ground._minZ = -ground._maxZ;
  60436. ground._setReady(false);
  60437. var onload = function (img) {
  60438. // Getting height map data
  60439. var canvas = document.createElement("canvas");
  60440. var context = canvas.getContext("2d");
  60441. if (!context) {
  60442. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60443. }
  60444. if (scene.isDisposed) {
  60445. return;
  60446. }
  60447. var bufferWidth = img.width;
  60448. var bufferHeight = img.height;
  60449. canvas.width = bufferWidth;
  60450. canvas.height = bufferHeight;
  60451. context.drawImage(img, 0, 0);
  60452. // Create VertexData from map data
  60453. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60454. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60455. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60456. width: width, height: height,
  60457. subdivisions: subdivisions,
  60458. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60459. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60460. });
  60461. vertexData.applyToMesh(ground, updatable);
  60462. //execute ready callback, if set
  60463. if (onReady) {
  60464. onReady(ground);
  60465. }
  60466. ground._setReady(true);
  60467. };
  60468. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60469. return ground;
  60470. };
  60471. /**
  60472. * Creates a polygon mesh
  60473. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60474. * * 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
  60475. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60476. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60477. * * 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)
  60478. * * Remember you can only change the shape positions, not their number when updating a polygon
  60479. * @param name defines the name of the mesh
  60480. * @param options defines the options used to create the mesh
  60481. * @param scene defines the hosting scene
  60482. * @returns the polygon mesh
  60483. */
  60484. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60485. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60486. var shape = options.shape;
  60487. var holes = options.holes || [];
  60488. var depth = options.depth || 0;
  60489. var contours = [];
  60490. var hole = [];
  60491. for (var i = 0; i < shape.length; i++) {
  60492. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60493. }
  60494. var epsilon = 0.00000001;
  60495. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60496. contours.pop();
  60497. }
  60498. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60499. for (var hNb = 0; hNb < holes.length; hNb++) {
  60500. hole = [];
  60501. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60502. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60503. }
  60504. polygonTriangulation.addHole(hole);
  60505. }
  60506. var polygon = polygonTriangulation.build(options.updatable, depth);
  60507. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60508. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60509. vertexData.applyToMesh(polygon, options.updatable);
  60510. return polygon;
  60511. };
  60512. ;
  60513. /**
  60514. * Creates an extruded polygon mesh, with depth in the Y direction.
  60515. * * 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)
  60516. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60517. * @param name defines the name of the mesh
  60518. * @param options defines the options used to create the mesh
  60519. * @param scene defines the hosting scene
  60520. * @returns the polygon mesh
  60521. */
  60522. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60523. return MeshBuilder.CreatePolygon(name, options, scene);
  60524. };
  60525. ;
  60526. /**
  60527. * Creates a tube mesh.
  60528. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60529. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60530. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60531. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60532. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60533. * * 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)
  60534. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60535. * * 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
  60536. * * 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
  60537. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60538. * * 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
  60539. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60540. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60541. * @param name defines the name of the mesh
  60542. * @param options defines the options used to create the mesh
  60543. * @param scene defines the hosting scene
  60544. * @returns the tube mesh
  60545. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60546. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60547. */
  60548. MeshBuilder.CreateTube = function (name, options, scene) {
  60549. var path = options.path;
  60550. var instance = options.instance;
  60551. var radius = 1.0;
  60552. if (instance) {
  60553. radius = instance.radius;
  60554. }
  60555. if (options.radius !== undefined) {
  60556. radius = options.radius;
  60557. }
  60558. ;
  60559. var tessellation = options.tessellation || 64 | 0;
  60560. var radiusFunction = options.radiusFunction || null;
  60561. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60562. var invertUV = options.invertUV || false;
  60563. var updatable = options.updatable;
  60564. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60565. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60566. // tube geometry
  60567. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60568. var tangents = path3D.getTangents();
  60569. var normals = path3D.getNormals();
  60570. var distances = path3D.getDistances();
  60571. var pi2 = Math.PI * 2;
  60572. var step = pi2 / tessellation * arc;
  60573. var returnRadius = function () { return radius; };
  60574. var radiusFunctionFinal = radiusFunction || returnRadius;
  60575. var circlePath;
  60576. var rad;
  60577. var normal;
  60578. var rotated;
  60579. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60580. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60581. for (var i = 0; i < path.length; i++) {
  60582. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60583. circlePath = Array(); // current circle array
  60584. normal = normals[i]; // current normal
  60585. for (var t = 0; t < tessellation; t++) {
  60586. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60587. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60588. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60589. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60590. circlePath[t] = rotated;
  60591. }
  60592. circlePaths[index] = circlePath;
  60593. index++;
  60594. }
  60595. // cap
  60596. var capPath = function (nbPoints, pathIndex) {
  60597. var pointCap = Array();
  60598. for (var i = 0; i < nbPoints; i++) {
  60599. pointCap.push(path[pathIndex]);
  60600. }
  60601. return pointCap;
  60602. };
  60603. switch (cap) {
  60604. case BABYLON.Mesh.NO_CAP:
  60605. break;
  60606. case BABYLON.Mesh.CAP_START:
  60607. circlePaths[0] = capPath(tessellation, 0);
  60608. circlePaths[1] = circlePaths[2].slice(0);
  60609. break;
  60610. case BABYLON.Mesh.CAP_END:
  60611. circlePaths[index] = circlePaths[index - 1].slice(0);
  60612. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60613. break;
  60614. case BABYLON.Mesh.CAP_ALL:
  60615. circlePaths[0] = capPath(tessellation, 0);
  60616. circlePaths[1] = circlePaths[2].slice(0);
  60617. circlePaths[index] = circlePaths[index - 1].slice(0);
  60618. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60619. break;
  60620. default:
  60621. break;
  60622. }
  60623. return circlePaths;
  60624. };
  60625. var path3D;
  60626. var pathArray;
  60627. if (instance) { // tube update
  60628. var arc = options.arc || instance.arc;
  60629. path3D = (instance.path3D).update(path);
  60630. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60631. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60632. instance.path3D = path3D;
  60633. instance.pathArray = pathArray;
  60634. instance.arc = arc;
  60635. instance.radius = radius;
  60636. return instance;
  60637. }
  60638. // tube creation
  60639. path3D = new BABYLON.Path3D(path);
  60640. var newPathArray = new Array();
  60641. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60642. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60643. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60644. tube.pathArray = pathArray;
  60645. tube.path3D = path3D;
  60646. tube.tessellation = tessellation;
  60647. tube.cap = cap;
  60648. tube.arc = options.arc;
  60649. tube.radius = radius;
  60650. return tube;
  60651. };
  60652. /**
  60653. * Creates a polyhedron mesh
  60654. * * 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
  60655. * * The parameter `size` (positive float, default 1) sets the polygon size
  60656. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60657. * * 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`
  60658. * * 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
  60659. * * 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)`)
  60660. * * 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
  60661. * * 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
  60662. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60663. * * 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
  60664. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60665. * @param name defines the name of the mesh
  60666. * @param options defines the options used to create the mesh
  60667. * @param scene defines the hosting scene
  60668. * @returns the polyhedron mesh
  60669. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  60670. */
  60671. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60672. var polyhedron = new BABYLON.Mesh(name, scene);
  60673. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60674. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60675. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60676. vertexData.applyToMesh(polyhedron, options.updatable);
  60677. return polyhedron;
  60678. };
  60679. /**
  60680. * Creates a decal mesh.
  60681. * 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
  60682. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60683. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60684. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60685. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60686. * @param name defines the name of the mesh
  60687. * @param sourceMesh defines the mesh where the decal must be applied
  60688. * @param options defines the options used to create the mesh
  60689. * @param scene defines the hosting scene
  60690. * @returns the decal mesh
  60691. * @see http://doc.babylonjs.com/how_to/decals
  60692. */
  60693. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60694. var indices = sourceMesh.getIndices();
  60695. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60696. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60697. var position = options.position || BABYLON.Vector3.Zero();
  60698. var normal = options.normal || BABYLON.Vector3.Up();
  60699. var size = options.size || BABYLON.Vector3.One();
  60700. var angle = options.angle || 0;
  60701. // Getting correct rotation
  60702. if (!normal) {
  60703. var target = new BABYLON.Vector3(0, 0, 1);
  60704. var camera = sourceMesh.getScene().activeCamera;
  60705. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60706. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60707. }
  60708. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60709. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60710. var pitch = Math.atan2(normal.y, len);
  60711. // Matrix
  60712. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60713. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60714. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60715. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60716. var vertexData = new BABYLON.VertexData();
  60717. vertexData.indices = [];
  60718. vertexData.positions = [];
  60719. vertexData.normals = [];
  60720. vertexData.uvs = [];
  60721. var currentVertexDataIndex = 0;
  60722. var extractDecalVector3 = function (indexId) {
  60723. var result = new BABYLON.PositionNormalVertex();
  60724. if (!indices || !positions || !normals) {
  60725. return result;
  60726. }
  60727. var vertexId = indices[indexId];
  60728. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60729. // Send vector to decal local world
  60730. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60731. // Get normal
  60732. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60733. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60734. return result;
  60735. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60736. var clip = function (vertices, axis) {
  60737. if (vertices.length === 0) {
  60738. return vertices;
  60739. }
  60740. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60741. var clipVertices = function (v0, v1) {
  60742. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60743. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60744. };
  60745. var result = new Array();
  60746. for (var index = 0; index < vertices.length; index += 3) {
  60747. var v1Out;
  60748. var v2Out;
  60749. var v3Out;
  60750. var total = 0;
  60751. var nV1 = null;
  60752. var nV2 = null;
  60753. var nV3 = null;
  60754. var nV4 = null;
  60755. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60756. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60757. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60758. v1Out = d1 > 0;
  60759. v2Out = d2 > 0;
  60760. v3Out = d3 > 0;
  60761. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60762. switch (total) {
  60763. case 0:
  60764. result.push(vertices[index]);
  60765. result.push(vertices[index + 1]);
  60766. result.push(vertices[index + 2]);
  60767. break;
  60768. case 1:
  60769. if (v1Out) {
  60770. nV1 = vertices[index + 1];
  60771. nV2 = vertices[index + 2];
  60772. nV3 = clipVertices(vertices[index], nV1);
  60773. nV4 = clipVertices(vertices[index], nV2);
  60774. }
  60775. if (v2Out) {
  60776. nV1 = vertices[index];
  60777. nV2 = vertices[index + 2];
  60778. nV3 = clipVertices(vertices[index + 1], nV1);
  60779. nV4 = clipVertices(vertices[index + 1], nV2);
  60780. result.push(nV3);
  60781. result.push(nV2.clone());
  60782. result.push(nV1.clone());
  60783. result.push(nV2.clone());
  60784. result.push(nV3.clone());
  60785. result.push(nV4);
  60786. break;
  60787. }
  60788. if (v3Out) {
  60789. nV1 = vertices[index];
  60790. nV2 = vertices[index + 1];
  60791. nV3 = clipVertices(vertices[index + 2], nV1);
  60792. nV4 = clipVertices(vertices[index + 2], nV2);
  60793. }
  60794. if (nV1 && nV2 && nV3 && nV4) {
  60795. result.push(nV1.clone());
  60796. result.push(nV2.clone());
  60797. result.push(nV3);
  60798. result.push(nV4);
  60799. result.push(nV3.clone());
  60800. result.push(nV2.clone());
  60801. }
  60802. break;
  60803. case 2:
  60804. if (!v1Out) {
  60805. nV1 = vertices[index].clone();
  60806. nV2 = clipVertices(nV1, vertices[index + 1]);
  60807. nV3 = clipVertices(nV1, vertices[index + 2]);
  60808. result.push(nV1);
  60809. result.push(nV2);
  60810. result.push(nV3);
  60811. }
  60812. if (!v2Out) {
  60813. nV1 = vertices[index + 1].clone();
  60814. nV2 = clipVertices(nV1, vertices[index + 2]);
  60815. nV3 = clipVertices(nV1, vertices[index]);
  60816. result.push(nV1);
  60817. result.push(nV2);
  60818. result.push(nV3);
  60819. }
  60820. if (!v3Out) {
  60821. nV1 = vertices[index + 2].clone();
  60822. nV2 = clipVertices(nV1, vertices[index]);
  60823. nV3 = clipVertices(nV1, vertices[index + 1]);
  60824. result.push(nV1);
  60825. result.push(nV2);
  60826. result.push(nV3);
  60827. }
  60828. break;
  60829. case 3:
  60830. break;
  60831. }
  60832. }
  60833. return result;
  60834. };
  60835. for (var index = 0; index < indices.length; index += 3) {
  60836. var faceVertices = new Array();
  60837. faceVertices.push(extractDecalVector3(index));
  60838. faceVertices.push(extractDecalVector3(index + 1));
  60839. faceVertices.push(extractDecalVector3(index + 2));
  60840. // Clip
  60841. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  60842. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  60843. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  60844. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  60845. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  60846. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  60847. if (faceVertices.length === 0) {
  60848. continue;
  60849. }
  60850. // Add UVs and get back to world
  60851. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  60852. var vertex = faceVertices[vIndex];
  60853. //TODO check for Int32Array | Uint32Array | Uint16Array
  60854. vertexData.indices.push(currentVertexDataIndex);
  60855. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  60856. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  60857. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  60858. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  60859. currentVertexDataIndex++;
  60860. }
  60861. }
  60862. // Return mesh
  60863. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  60864. vertexData.applyToMesh(decal);
  60865. decal.position = position.clone();
  60866. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  60867. return decal;
  60868. };
  60869. // Privates
  60870. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  60871. // extrusion geometry
  60872. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  60873. var tangents = path3D.getTangents();
  60874. var normals = path3D.getNormals();
  60875. var binormals = path3D.getBinormals();
  60876. var distances = path3D.getDistances();
  60877. var angle = 0;
  60878. var returnScale = function () { return scale !== null ? scale : 1; };
  60879. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  60880. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  60881. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  60882. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60883. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60884. for (var i = 0; i < curve.length; i++) {
  60885. var shapePath = new Array();
  60886. var angleStep = rotate(i, distances[i]);
  60887. var scaleRatio = scl(i, distances[i]);
  60888. for (var p = 0; p < shape.length; p++) {
  60889. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  60890. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  60891. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  60892. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  60893. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  60894. shapePath[p] = rotated;
  60895. }
  60896. shapePaths[index] = shapePath;
  60897. angle += angleStep;
  60898. index++;
  60899. }
  60900. // cap
  60901. var capPath = function (shapePath) {
  60902. var pointCap = Array();
  60903. var barycenter = BABYLON.Vector3.Zero();
  60904. var i;
  60905. for (i = 0; i < shapePath.length; i++) {
  60906. barycenter.addInPlace(shapePath[i]);
  60907. }
  60908. barycenter.scaleInPlace(1.0 / shapePath.length);
  60909. for (i = 0; i < shapePath.length; i++) {
  60910. pointCap.push(barycenter);
  60911. }
  60912. return pointCap;
  60913. };
  60914. switch (cap) {
  60915. case BABYLON.Mesh.NO_CAP:
  60916. break;
  60917. case BABYLON.Mesh.CAP_START:
  60918. shapePaths[0] = capPath(shapePaths[2]);
  60919. shapePaths[1] = shapePaths[2];
  60920. break;
  60921. case BABYLON.Mesh.CAP_END:
  60922. shapePaths[index] = shapePaths[index - 1];
  60923. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60924. break;
  60925. case BABYLON.Mesh.CAP_ALL:
  60926. shapePaths[0] = capPath(shapePaths[2]);
  60927. shapePaths[1] = shapePaths[2];
  60928. shapePaths[index] = shapePaths[index - 1];
  60929. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60930. break;
  60931. default:
  60932. break;
  60933. }
  60934. return shapePaths;
  60935. };
  60936. var path3D;
  60937. var pathArray;
  60938. if (instance) { // instance update
  60939. path3D = (instance.path3D).update(curve);
  60940. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  60941. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  60942. return instance;
  60943. }
  60944. // extruded shape creation
  60945. path3D = new BABYLON.Path3D(curve);
  60946. var newShapePaths = new Array();
  60947. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60948. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  60949. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  60950. extrudedGeneric.pathArray = pathArray;
  60951. extrudedGeneric.path3D = path3D;
  60952. extrudedGeneric.cap = cap;
  60953. return extrudedGeneric;
  60954. };
  60955. return MeshBuilder;
  60956. }());
  60957. BABYLON.MeshBuilder = MeshBuilder;
  60958. })(BABYLON || (BABYLON = {}));
  60959. //# sourceMappingURL=babylon.meshBuilder.js.map
  60960. var BABYLON;
  60961. (function (BABYLON) {
  60962. /**
  60963. * Draco compression (https://google.github.io/draco/)
  60964. *
  60965. * This class wraps the Draco module.
  60966. *
  60967. * **Encoder**
  60968. *
  60969. * The encoder is not currently implemented.
  60970. *
  60971. * **Decoder**
  60972. *
  60973. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  60974. *
  60975. * To update the configuration, use the following code:
  60976. * ```javascript
  60977. * BABYLON.DracoCompression.Configuration = {
  60978. * decoder: {
  60979. * wasmUrl: "<url to the WebAssembly library>",
  60980. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  60981. * fallbackUrl: "<url to the fallback JavaScript library>",
  60982. * }
  60983. * };
  60984. * ```
  60985. *
  60986. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  60987. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  60988. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  60989. *
  60990. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  60991. * ```javascript
  60992. * var dracoCompression = new BABYLON.DracoCompression();
  60993. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  60994. * [BABYLON.VertexBuffer.PositionKind]: 0
  60995. * });
  60996. * ```
  60997. *
  60998. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  60999. */
  61000. var DracoCompression = /** @class */ (function () {
  61001. /**
  61002. * Constructor
  61003. */
  61004. function DracoCompression() {
  61005. }
  61006. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61007. /**
  61008. * Returns true if the decoder is available.
  61009. */
  61010. get: function () {
  61011. if (typeof DracoDecoderModule !== "undefined") {
  61012. return true;
  61013. }
  61014. var decoder = DracoCompression.Configuration.decoder;
  61015. if (decoder) {
  61016. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61017. return true;
  61018. }
  61019. if (decoder.fallbackUrl) {
  61020. return true;
  61021. }
  61022. }
  61023. return false;
  61024. },
  61025. enumerable: true,
  61026. configurable: true
  61027. });
  61028. /**
  61029. * Stop all async operations and release resources.
  61030. */
  61031. DracoCompression.prototype.dispose = function () {
  61032. };
  61033. /**
  61034. * Decode Draco compressed mesh data to vertex data.
  61035. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61036. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61037. * @returns A promise that resolves with the decoded vertex data
  61038. */
  61039. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61040. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61041. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61042. var module = wrappedModule.module;
  61043. var vertexData = new BABYLON.VertexData();
  61044. var buffer = new module.DecoderBuffer();
  61045. buffer.Init(dataView, dataView.byteLength);
  61046. var decoder = new module.Decoder();
  61047. var geometry;
  61048. var status;
  61049. try {
  61050. var type = decoder.GetEncodedGeometryType(buffer);
  61051. switch (type) {
  61052. case module.TRIANGULAR_MESH:
  61053. geometry = new module.Mesh();
  61054. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61055. break;
  61056. case module.POINT_CLOUD:
  61057. geometry = new module.PointCloud();
  61058. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61059. break;
  61060. default:
  61061. throw new Error("Invalid geometry type " + type);
  61062. }
  61063. if (!status.ok() || !geometry.ptr) {
  61064. throw new Error(status.error_msg());
  61065. }
  61066. var numPoints = geometry.num_points();
  61067. if (type === module.TRIANGULAR_MESH) {
  61068. var numFaces = geometry.num_faces();
  61069. var faceIndices = new module.DracoInt32Array();
  61070. try {
  61071. var indices = new Uint32Array(numFaces * 3);
  61072. for (var i = 0; i < numFaces; i++) {
  61073. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61074. var offset = i * 3;
  61075. indices[offset + 0] = faceIndices.GetValue(0);
  61076. indices[offset + 1] = faceIndices.GetValue(1);
  61077. indices[offset + 2] = faceIndices.GetValue(2);
  61078. }
  61079. vertexData.indices = indices;
  61080. }
  61081. finally {
  61082. module.destroy(faceIndices);
  61083. }
  61084. }
  61085. for (var kind in attributes) {
  61086. var uniqueId = attributes[kind];
  61087. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61088. var dracoData = new module.DracoFloat32Array();
  61089. try {
  61090. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61091. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61092. for (var i = 0; i < babylonData.length; i++) {
  61093. babylonData[i] = dracoData.GetValue(i);
  61094. }
  61095. vertexData.set(babylonData, kind);
  61096. }
  61097. finally {
  61098. module.destroy(dracoData);
  61099. }
  61100. }
  61101. }
  61102. finally {
  61103. if (geometry) {
  61104. module.destroy(geometry);
  61105. }
  61106. module.destroy(decoder);
  61107. module.destroy(buffer);
  61108. }
  61109. return vertexData;
  61110. });
  61111. };
  61112. DracoCompression._GetDecoderModule = function () {
  61113. if (!DracoCompression._DecoderModulePromise) {
  61114. var promise = null;
  61115. var config_1 = {};
  61116. if (typeof DracoDecoderModule !== "undefined") {
  61117. promise = Promise.resolve();
  61118. }
  61119. else {
  61120. var decoder = DracoCompression.Configuration.decoder;
  61121. if (decoder) {
  61122. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61123. promise = Promise.all([
  61124. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61125. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61126. config_1.wasmBinary = data;
  61127. })
  61128. ]);
  61129. }
  61130. else if (decoder.fallbackUrl) {
  61131. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61132. }
  61133. }
  61134. }
  61135. if (!promise) {
  61136. throw new Error("Draco decoder module is not available");
  61137. }
  61138. DracoCompression._DecoderModulePromise = promise.then(function () {
  61139. return new Promise(function (resolve) {
  61140. config_1.onModuleLoaded = function (decoderModule) {
  61141. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61142. resolve({ module: decoderModule });
  61143. };
  61144. DracoDecoderModule(config_1);
  61145. });
  61146. });
  61147. }
  61148. return DracoCompression._DecoderModulePromise;
  61149. };
  61150. DracoCompression._LoadScriptAsync = function (url) {
  61151. return new Promise(function (resolve, reject) {
  61152. BABYLON.Tools.LoadScript(url, function () {
  61153. resolve();
  61154. }, function (message) {
  61155. reject(new Error(message));
  61156. });
  61157. });
  61158. };
  61159. DracoCompression._LoadFileAsync = function (url) {
  61160. return new Promise(function (resolve, reject) {
  61161. BABYLON.Tools.LoadFile(url, function (data) {
  61162. resolve(data);
  61163. }, undefined, undefined, true, function (request, exception) {
  61164. reject(exception);
  61165. });
  61166. });
  61167. };
  61168. /**
  61169. * The configuration. Defaults to the following urls:
  61170. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61171. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61172. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61173. */
  61174. DracoCompression.Configuration = {
  61175. decoder: {
  61176. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61177. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61178. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61179. }
  61180. };
  61181. return DracoCompression;
  61182. }());
  61183. BABYLON.DracoCompression = DracoCompression;
  61184. })(BABYLON || (BABYLON = {}));
  61185. //# sourceMappingURL=babylon.dracoCompression.js.map
  61186. var BABYLON;
  61187. (function (BABYLON) {
  61188. var AudioEngine = /** @class */ (function () {
  61189. function AudioEngine() {
  61190. this._audioContext = null;
  61191. this._audioContextInitialized = false;
  61192. this.canUseWebAudio = false;
  61193. this.WarnedWebAudioUnsupported = false;
  61194. this.unlocked = false;
  61195. this.isMP3supported = false;
  61196. this.isOGGsupported = false;
  61197. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61198. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61199. this.canUseWebAudio = true;
  61200. }
  61201. var audioElem = document.createElement('audio');
  61202. try {
  61203. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61204. this.isMP3supported = true;
  61205. }
  61206. }
  61207. catch (e) {
  61208. // protect error during capability check.
  61209. }
  61210. try {
  61211. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61212. this.isOGGsupported = true;
  61213. }
  61214. }
  61215. catch (e) {
  61216. // protect error during capability check.
  61217. }
  61218. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61219. this._unlockiOSaudio();
  61220. }
  61221. else {
  61222. this.unlocked = true;
  61223. }
  61224. }
  61225. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61226. get: function () {
  61227. if (!this._audioContextInitialized) {
  61228. this._initializeAudioContext();
  61229. }
  61230. return this._audioContext;
  61231. },
  61232. enumerable: true,
  61233. configurable: true
  61234. });
  61235. AudioEngine.prototype._unlockiOSaudio = function () {
  61236. var _this = this;
  61237. var unlockaudio = function () {
  61238. if (!_this.audioContext) {
  61239. return;
  61240. }
  61241. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61242. var source = _this.audioContext.createBufferSource();
  61243. source.buffer = buffer;
  61244. source.connect(_this.audioContext.destination);
  61245. source.start(0);
  61246. setTimeout(function () {
  61247. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61248. _this.unlocked = true;
  61249. window.removeEventListener('touchend', unlockaudio, false);
  61250. if (_this.onAudioUnlocked) {
  61251. _this.onAudioUnlocked();
  61252. }
  61253. }
  61254. }, 0);
  61255. };
  61256. window.addEventListener('touchend', unlockaudio, false);
  61257. };
  61258. AudioEngine.prototype._initializeAudioContext = function () {
  61259. try {
  61260. if (this.canUseWebAudio) {
  61261. this._audioContext = new AudioContext();
  61262. // create a global volume gain node
  61263. this.masterGain = this._audioContext.createGain();
  61264. this.masterGain.gain.value = 1;
  61265. this.masterGain.connect(this._audioContext.destination);
  61266. this._audioContextInitialized = true;
  61267. }
  61268. }
  61269. catch (e) {
  61270. this.canUseWebAudio = false;
  61271. BABYLON.Tools.Error("Web Audio: " + e.message);
  61272. }
  61273. };
  61274. AudioEngine.prototype.dispose = function () {
  61275. if (this.canUseWebAudio && this._audioContextInitialized) {
  61276. if (this._connectedAnalyser && this._audioContext) {
  61277. this._connectedAnalyser.stopDebugCanvas();
  61278. this._connectedAnalyser.dispose();
  61279. this.masterGain.disconnect();
  61280. this.masterGain.connect(this._audioContext.destination);
  61281. this._connectedAnalyser = null;
  61282. }
  61283. this.masterGain.gain.value = 1;
  61284. }
  61285. this.WarnedWebAudioUnsupported = false;
  61286. };
  61287. AudioEngine.prototype.getGlobalVolume = function () {
  61288. if (this.canUseWebAudio && this._audioContextInitialized) {
  61289. return this.masterGain.gain.value;
  61290. }
  61291. else {
  61292. return -1;
  61293. }
  61294. };
  61295. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61296. if (this.canUseWebAudio && this._audioContextInitialized) {
  61297. this.masterGain.gain.value = newVolume;
  61298. }
  61299. };
  61300. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61301. if (this._connectedAnalyser) {
  61302. this._connectedAnalyser.stopDebugCanvas();
  61303. }
  61304. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61305. this._connectedAnalyser = analyser;
  61306. this.masterGain.disconnect();
  61307. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61308. }
  61309. };
  61310. return AudioEngine;
  61311. }());
  61312. BABYLON.AudioEngine = AudioEngine;
  61313. })(BABYLON || (BABYLON = {}));
  61314. //# sourceMappingURL=babylon.audioEngine.js.map
  61315. var BABYLON;
  61316. (function (BABYLON) {
  61317. var Sound = /** @class */ (function () {
  61318. /**
  61319. * Create a sound and attach it to a scene
  61320. * @param name Name of your sound
  61321. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61322. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61323. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61324. */
  61325. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61326. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61327. var _this = this;
  61328. this.autoplay = false;
  61329. this.loop = false;
  61330. this.useCustomAttenuation = false;
  61331. this.spatialSound = false;
  61332. this.refDistance = 1;
  61333. this.rolloffFactor = 1;
  61334. this.maxDistance = 100;
  61335. this.distanceModel = "linear";
  61336. this._panningModel = "equalpower";
  61337. this._playbackRate = 1;
  61338. this._streaming = false;
  61339. this._startTime = 0;
  61340. this._startOffset = 0;
  61341. this._position = BABYLON.Vector3.Zero();
  61342. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61343. this._volume = 1;
  61344. this._isReadyToPlay = false;
  61345. this.isPlaying = false;
  61346. this.isPaused = false;
  61347. this._isDirectional = false;
  61348. // Used if you'd like to create a directional sound.
  61349. // If not set, the sound will be omnidirectional
  61350. this._coneInnerAngle = 360;
  61351. this._coneOuterAngle = 360;
  61352. this._coneOuterGain = 0;
  61353. this._isOutputConnected = false;
  61354. this._urlType = "Unknown";
  61355. this.name = name;
  61356. this._scene = scene;
  61357. this._readyToPlayCallback = readyToPlayCallback;
  61358. // Default custom attenuation function is a linear attenuation
  61359. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61360. if (currentDistance < maxDistance) {
  61361. return currentVolume * (1 - currentDistance / maxDistance);
  61362. }
  61363. else {
  61364. return 0;
  61365. }
  61366. };
  61367. if (options) {
  61368. this.autoplay = options.autoplay || false;
  61369. this.loop = options.loop || false;
  61370. // if volume === 0, we need another way to check this option
  61371. if (options.volume !== undefined) {
  61372. this._volume = options.volume;
  61373. }
  61374. this.spatialSound = options.spatialSound || false;
  61375. this.maxDistance = options.maxDistance || 100;
  61376. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61377. this.rolloffFactor = options.rolloffFactor || 1;
  61378. this.refDistance = options.refDistance || 1;
  61379. this.distanceModel = options.distanceModel || "linear";
  61380. this._playbackRate = options.playbackRate || 1;
  61381. this._streaming = options.streaming || false;
  61382. }
  61383. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61384. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61385. this._soundGain.gain.value = this._volume;
  61386. this._inputAudioNode = this._soundGain;
  61387. this._ouputAudioNode = this._soundGain;
  61388. if (this.spatialSound) {
  61389. this._createSpatialParameters();
  61390. }
  61391. this._scene.mainSoundTrack.AddSound(this);
  61392. var validParameter = true;
  61393. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61394. if (urlOrArrayBuffer) {
  61395. try {
  61396. if (typeof (urlOrArrayBuffer) === "string")
  61397. this._urlType = "String";
  61398. if (Array.isArray(urlOrArrayBuffer))
  61399. this._urlType = "Array";
  61400. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61401. this._urlType = "ArrayBuffer";
  61402. var urls = [];
  61403. var codecSupportedFound = false;
  61404. switch (this._urlType) {
  61405. case "ArrayBuffer":
  61406. if (urlOrArrayBuffer.byteLength > 0) {
  61407. codecSupportedFound = true;
  61408. this._soundLoaded(urlOrArrayBuffer);
  61409. }
  61410. break;
  61411. case "String":
  61412. urls.push(urlOrArrayBuffer);
  61413. case "Array":
  61414. if (urls.length === 0)
  61415. urls = urlOrArrayBuffer;
  61416. // If we found a supported format, we load it immediately and stop the loop
  61417. for (var i = 0; i < urls.length; i++) {
  61418. var url = urls[i];
  61419. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61420. codecSupportedFound = true;
  61421. }
  61422. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61423. codecSupportedFound = true;
  61424. }
  61425. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61426. codecSupportedFound = true;
  61427. }
  61428. if (url.indexOf("blob:") !== -1) {
  61429. codecSupportedFound = true;
  61430. }
  61431. if (codecSupportedFound) {
  61432. // Loading sound using XHR2
  61433. if (!this._streaming) {
  61434. this._scene._loadFile(url, function (data) {
  61435. _this._soundLoaded(data);
  61436. }, undefined, true, true, function (exception) {
  61437. if (exception) {
  61438. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61439. }
  61440. BABYLON.Tools.Error("Sound creation aborted.");
  61441. _this._scene.mainSoundTrack.RemoveSound(_this);
  61442. });
  61443. }
  61444. // Streaming sound using HTML5 Audio tag
  61445. else {
  61446. this._htmlAudioElement = new Audio(url);
  61447. this._htmlAudioElement.controls = false;
  61448. this._htmlAudioElement.loop = this.loop;
  61449. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61450. this._htmlAudioElement.preload = "auto";
  61451. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61452. _this._isReadyToPlay = true;
  61453. if (_this.autoplay) {
  61454. _this.play();
  61455. }
  61456. if (_this._readyToPlayCallback) {
  61457. _this._readyToPlayCallback();
  61458. }
  61459. });
  61460. document.body.appendChild(this._htmlAudioElement);
  61461. }
  61462. break;
  61463. }
  61464. }
  61465. break;
  61466. default:
  61467. validParameter = false;
  61468. break;
  61469. }
  61470. if (!validParameter) {
  61471. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61472. }
  61473. else {
  61474. if (!codecSupportedFound) {
  61475. this._isReadyToPlay = true;
  61476. // Simulating a ready to play event to avoid breaking code path
  61477. if (this._readyToPlayCallback) {
  61478. window.setTimeout(function () {
  61479. if (_this._readyToPlayCallback) {
  61480. _this._readyToPlayCallback();
  61481. }
  61482. }, 1000);
  61483. }
  61484. }
  61485. }
  61486. }
  61487. catch (ex) {
  61488. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61489. this._scene.mainSoundTrack.RemoveSound(this);
  61490. }
  61491. }
  61492. }
  61493. else {
  61494. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61495. this._scene.mainSoundTrack.AddSound(this);
  61496. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61497. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61498. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61499. }
  61500. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61501. if (this._readyToPlayCallback) {
  61502. window.setTimeout(function () {
  61503. if (_this._readyToPlayCallback) {
  61504. _this._readyToPlayCallback();
  61505. }
  61506. }, 1000);
  61507. }
  61508. }
  61509. }
  61510. Sound.prototype.dispose = function () {
  61511. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61512. if (this.isPlaying) {
  61513. this.stop();
  61514. }
  61515. this._isReadyToPlay = false;
  61516. if (this.soundTrackId === -1) {
  61517. this._scene.mainSoundTrack.RemoveSound(this);
  61518. }
  61519. else {
  61520. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61521. }
  61522. if (this._soundGain) {
  61523. this._soundGain.disconnect();
  61524. this._soundGain = null;
  61525. }
  61526. if (this._soundPanner) {
  61527. this._soundPanner.disconnect();
  61528. this._soundPanner = null;
  61529. }
  61530. if (this._soundSource) {
  61531. this._soundSource.disconnect();
  61532. this._soundSource = null;
  61533. }
  61534. this._audioBuffer = null;
  61535. if (this._htmlAudioElement) {
  61536. this._htmlAudioElement.pause();
  61537. this._htmlAudioElement.src = "";
  61538. document.body.removeChild(this._htmlAudioElement);
  61539. }
  61540. if (this._connectedMesh && this._registerFunc) {
  61541. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61542. this._connectedMesh = null;
  61543. }
  61544. }
  61545. };
  61546. Sound.prototype.isReady = function () {
  61547. return this._isReadyToPlay;
  61548. };
  61549. Sound.prototype._soundLoaded = function (audioData) {
  61550. var _this = this;
  61551. if (!BABYLON.Engine.audioEngine.audioContext) {
  61552. return;
  61553. }
  61554. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61555. _this._audioBuffer = buffer;
  61556. _this._isReadyToPlay = true;
  61557. if (_this.autoplay) {
  61558. _this.play();
  61559. }
  61560. if (_this._readyToPlayCallback) {
  61561. _this._readyToPlayCallback();
  61562. }
  61563. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61564. };
  61565. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61566. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61567. this._audioBuffer = audioBuffer;
  61568. this._isReadyToPlay = true;
  61569. }
  61570. };
  61571. Sound.prototype.updateOptions = function (options) {
  61572. if (options) {
  61573. this.loop = options.loop || this.loop;
  61574. this.maxDistance = options.maxDistance || this.maxDistance;
  61575. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61576. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61577. this.refDistance = options.refDistance || this.refDistance;
  61578. this.distanceModel = options.distanceModel || this.distanceModel;
  61579. this._playbackRate = options.playbackRate || this._playbackRate;
  61580. this._updateSpatialParameters();
  61581. if (this.isPlaying) {
  61582. if (this._streaming) {
  61583. this._htmlAudioElement.playbackRate = this._playbackRate;
  61584. }
  61585. else {
  61586. if (this._soundSource) {
  61587. this._soundSource.playbackRate.value = this._playbackRate;
  61588. }
  61589. }
  61590. }
  61591. }
  61592. };
  61593. Sound.prototype._createSpatialParameters = function () {
  61594. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61595. if (this._scene.headphone) {
  61596. this._panningModel = "HRTF";
  61597. }
  61598. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61599. this._updateSpatialParameters();
  61600. this._soundPanner.connect(this._ouputAudioNode);
  61601. this._inputAudioNode = this._soundPanner;
  61602. }
  61603. };
  61604. Sound.prototype._updateSpatialParameters = function () {
  61605. if (this.spatialSound && this._soundPanner) {
  61606. if (this.useCustomAttenuation) {
  61607. // Tricks to disable in a way embedded Web Audio attenuation
  61608. this._soundPanner.distanceModel = "linear";
  61609. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61610. this._soundPanner.refDistance = 1;
  61611. this._soundPanner.rolloffFactor = 1;
  61612. this._soundPanner.panningModel = this._panningModel;
  61613. }
  61614. else {
  61615. this._soundPanner.distanceModel = this.distanceModel;
  61616. this._soundPanner.maxDistance = this.maxDistance;
  61617. this._soundPanner.refDistance = this.refDistance;
  61618. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61619. this._soundPanner.panningModel = this._panningModel;
  61620. }
  61621. }
  61622. };
  61623. Sound.prototype.switchPanningModelToHRTF = function () {
  61624. this._panningModel = "HRTF";
  61625. this._switchPanningModel();
  61626. };
  61627. Sound.prototype.switchPanningModelToEqualPower = function () {
  61628. this._panningModel = "equalpower";
  61629. this._switchPanningModel();
  61630. };
  61631. Sound.prototype._switchPanningModel = function () {
  61632. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61633. this._soundPanner.panningModel = this._panningModel;
  61634. }
  61635. };
  61636. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61637. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61638. if (this._isOutputConnected) {
  61639. this._ouputAudioNode.disconnect();
  61640. }
  61641. this._ouputAudioNode.connect(soundTrackAudioNode);
  61642. this._isOutputConnected = true;
  61643. }
  61644. };
  61645. /**
  61646. * Transform this sound into a directional source
  61647. * @param coneInnerAngle Size of the inner cone in degree
  61648. * @param coneOuterAngle Size of the outer cone in degree
  61649. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61650. */
  61651. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61652. if (coneOuterAngle < coneInnerAngle) {
  61653. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61654. return;
  61655. }
  61656. this._coneInnerAngle = coneInnerAngle;
  61657. this._coneOuterAngle = coneOuterAngle;
  61658. this._coneOuterGain = coneOuterGain;
  61659. this._isDirectional = true;
  61660. if (this.isPlaying && this.loop) {
  61661. this.stop();
  61662. this.play();
  61663. }
  61664. };
  61665. Sound.prototype.setPosition = function (newPosition) {
  61666. this._position = newPosition;
  61667. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61668. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61669. }
  61670. };
  61671. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61672. this._localDirection = newLocalDirection;
  61673. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61674. this._updateDirection();
  61675. }
  61676. };
  61677. Sound.prototype._updateDirection = function () {
  61678. if (!this._connectedMesh || !this._soundPanner) {
  61679. return;
  61680. }
  61681. var mat = this._connectedMesh.getWorldMatrix();
  61682. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61683. direction.normalize();
  61684. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61685. };
  61686. Sound.prototype.updateDistanceFromListener = function () {
  61687. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61688. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61689. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61690. }
  61691. };
  61692. Sound.prototype.setAttenuationFunction = function (callback) {
  61693. this._customAttenuationFunction = callback;
  61694. };
  61695. /**
  61696. * Play the sound
  61697. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61698. * @param offset (optional) Start the sound setting it at a specific time
  61699. */
  61700. Sound.prototype.play = function (time, offset) {
  61701. var _this = this;
  61702. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61703. try {
  61704. if (this._startOffset < 0) {
  61705. time = -this._startOffset;
  61706. this._startOffset = 0;
  61707. }
  61708. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61709. if (!this._soundSource || !this._streamingSource) {
  61710. if (this.spatialSound && this._soundPanner) {
  61711. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61712. if (this._isDirectional) {
  61713. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61714. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61715. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61716. if (this._connectedMesh) {
  61717. this._updateDirection();
  61718. }
  61719. else {
  61720. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61721. }
  61722. }
  61723. }
  61724. }
  61725. if (this._streaming) {
  61726. if (!this._streamingSource) {
  61727. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61728. this._htmlAudioElement.onended = function () { _this._onended(); };
  61729. this._htmlAudioElement.playbackRate = this._playbackRate;
  61730. }
  61731. this._streamingSource.disconnect();
  61732. this._streamingSource.connect(this._inputAudioNode);
  61733. this._htmlAudioElement.play();
  61734. }
  61735. else {
  61736. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61737. this._soundSource.buffer = this._audioBuffer;
  61738. this._soundSource.connect(this._inputAudioNode);
  61739. this._soundSource.loop = this.loop;
  61740. this._soundSource.playbackRate.value = this._playbackRate;
  61741. this._soundSource.onended = function () { _this._onended(); };
  61742. if (this._soundSource.buffer) {
  61743. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61744. }
  61745. }
  61746. this._startTime = startTime;
  61747. this.isPlaying = true;
  61748. this.isPaused = false;
  61749. }
  61750. catch (ex) {
  61751. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61752. }
  61753. }
  61754. };
  61755. Sound.prototype._onended = function () {
  61756. this.isPlaying = false;
  61757. if (this.onended) {
  61758. this.onended();
  61759. }
  61760. };
  61761. /**
  61762. * Stop the sound
  61763. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61764. */
  61765. Sound.prototype.stop = function (time) {
  61766. if (this.isPlaying) {
  61767. if (this._streaming) {
  61768. this._htmlAudioElement.pause();
  61769. // Test needed for Firefox or it will generate an Invalid State Error
  61770. if (this._htmlAudioElement.currentTime > 0) {
  61771. this._htmlAudioElement.currentTime = 0;
  61772. }
  61773. }
  61774. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61775. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61776. this._soundSource.stop(stopTime);
  61777. this._soundSource.onended = function () { };
  61778. if (!this.isPaused) {
  61779. this._startOffset = 0;
  61780. }
  61781. }
  61782. this.isPlaying = false;
  61783. }
  61784. };
  61785. Sound.prototype.pause = function () {
  61786. if (this.isPlaying) {
  61787. this.isPaused = true;
  61788. if (this._streaming) {
  61789. this._htmlAudioElement.pause();
  61790. }
  61791. else if (BABYLON.Engine.audioEngine.audioContext) {
  61792. this.stop(0);
  61793. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61794. }
  61795. }
  61796. };
  61797. Sound.prototype.setVolume = function (newVolume, time) {
  61798. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61799. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61800. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61801. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61802. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61803. }
  61804. else {
  61805. this._soundGain.gain.value = newVolume;
  61806. }
  61807. }
  61808. this._volume = newVolume;
  61809. };
  61810. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  61811. this._playbackRate = newPlaybackRate;
  61812. if (this.isPlaying) {
  61813. if (this._streaming) {
  61814. this._htmlAudioElement.playbackRate = this._playbackRate;
  61815. }
  61816. else if (this._soundSource) {
  61817. this._soundSource.playbackRate.value = this._playbackRate;
  61818. }
  61819. }
  61820. };
  61821. Sound.prototype.getVolume = function () {
  61822. return this._volume;
  61823. };
  61824. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  61825. var _this = this;
  61826. if (this._connectedMesh && this._registerFunc) {
  61827. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61828. this._registerFunc = null;
  61829. }
  61830. this._connectedMesh = meshToConnectTo;
  61831. if (!this.spatialSound) {
  61832. this.spatialSound = true;
  61833. this._createSpatialParameters();
  61834. if (this.isPlaying && this.loop) {
  61835. this.stop();
  61836. this.play();
  61837. }
  61838. }
  61839. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  61840. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  61841. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  61842. };
  61843. Sound.prototype.detachFromMesh = function () {
  61844. if (this._connectedMesh && this._registerFunc) {
  61845. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61846. this._registerFunc = null;
  61847. this._connectedMesh = null;
  61848. }
  61849. };
  61850. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  61851. if (!node.getBoundingInfo) {
  61852. return;
  61853. }
  61854. var mesh = node;
  61855. var boundingInfo = mesh.getBoundingInfo();
  61856. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  61857. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  61858. this._updateDirection();
  61859. }
  61860. };
  61861. Sound.prototype.clone = function () {
  61862. var _this = this;
  61863. if (!this._streaming) {
  61864. var setBufferAndRun = function () {
  61865. if (_this._isReadyToPlay) {
  61866. clonedSound._audioBuffer = _this.getAudioBuffer();
  61867. clonedSound._isReadyToPlay = true;
  61868. if (clonedSound.autoplay) {
  61869. clonedSound.play();
  61870. }
  61871. }
  61872. else {
  61873. window.setTimeout(setBufferAndRun, 300);
  61874. }
  61875. };
  61876. var currentOptions = {
  61877. autoplay: this.autoplay, loop: this.loop,
  61878. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  61879. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  61880. refDistance: this.refDistance, distanceModel: this.distanceModel
  61881. };
  61882. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  61883. if (this.useCustomAttenuation) {
  61884. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  61885. }
  61886. clonedSound.setPosition(this._position);
  61887. clonedSound.setPlaybackRate(this._playbackRate);
  61888. setBufferAndRun();
  61889. return clonedSound;
  61890. }
  61891. // Can't clone a streaming sound
  61892. else {
  61893. return null;
  61894. }
  61895. };
  61896. Sound.prototype.getAudioBuffer = function () {
  61897. return this._audioBuffer;
  61898. };
  61899. Sound.prototype.serialize = function () {
  61900. var serializationObject = {
  61901. name: this.name,
  61902. url: this.name,
  61903. autoplay: this.autoplay,
  61904. loop: this.loop,
  61905. volume: this._volume,
  61906. spatialSound: this.spatialSound,
  61907. maxDistance: this.maxDistance,
  61908. rolloffFactor: this.rolloffFactor,
  61909. refDistance: this.refDistance,
  61910. distanceModel: this.distanceModel,
  61911. playbackRate: this._playbackRate,
  61912. panningModel: this._panningModel,
  61913. soundTrackId: this.soundTrackId
  61914. };
  61915. if (this.spatialSound) {
  61916. if (this._connectedMesh)
  61917. serializationObject.connectedMeshId = this._connectedMesh.id;
  61918. serializationObject.position = this._position.asArray();
  61919. serializationObject.refDistance = this.refDistance;
  61920. serializationObject.distanceModel = this.distanceModel;
  61921. serializationObject.isDirectional = this._isDirectional;
  61922. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  61923. serializationObject.coneInnerAngle = this._coneInnerAngle;
  61924. serializationObject.coneOuterAngle = this._coneOuterAngle;
  61925. serializationObject.coneOuterGain = this._coneOuterGain;
  61926. }
  61927. return serializationObject;
  61928. };
  61929. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  61930. var soundName = parsedSound.name;
  61931. var soundUrl;
  61932. if (parsedSound.url) {
  61933. soundUrl = rootUrl + parsedSound.url;
  61934. }
  61935. else {
  61936. soundUrl = rootUrl + soundName;
  61937. }
  61938. var options = {
  61939. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  61940. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  61941. rolloffFactor: parsedSound.rolloffFactor,
  61942. refDistance: parsedSound.refDistance,
  61943. distanceModel: parsedSound.distanceModel,
  61944. playbackRate: parsedSound.playbackRate
  61945. };
  61946. var newSound;
  61947. if (!sourceSound) {
  61948. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  61949. scene._addPendingData(newSound);
  61950. }
  61951. else {
  61952. var setBufferAndRun = function () {
  61953. if (sourceSound._isReadyToPlay) {
  61954. newSound._audioBuffer = sourceSound.getAudioBuffer();
  61955. newSound._isReadyToPlay = true;
  61956. if (newSound.autoplay) {
  61957. newSound.play();
  61958. }
  61959. }
  61960. else {
  61961. window.setTimeout(setBufferAndRun, 300);
  61962. }
  61963. };
  61964. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  61965. setBufferAndRun();
  61966. }
  61967. if (parsedSound.position) {
  61968. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  61969. newSound.setPosition(soundPosition);
  61970. }
  61971. if (parsedSound.isDirectional) {
  61972. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  61973. if (parsedSound.localDirectionToMesh) {
  61974. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  61975. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  61976. }
  61977. }
  61978. if (parsedSound.connectedMeshId) {
  61979. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  61980. if (connectedMesh) {
  61981. newSound.attachToMesh(connectedMesh);
  61982. }
  61983. }
  61984. return newSound;
  61985. };
  61986. return Sound;
  61987. }());
  61988. BABYLON.Sound = Sound;
  61989. })(BABYLON || (BABYLON = {}));
  61990. //# sourceMappingURL=babylon.sound.js.map
  61991. var BABYLON;
  61992. (function (BABYLON) {
  61993. var SoundTrack = /** @class */ (function () {
  61994. function SoundTrack(scene, options) {
  61995. this.id = -1;
  61996. this._isMainTrack = false;
  61997. this._isInitialized = false;
  61998. this._scene = scene;
  61999. this.soundCollection = new Array();
  62000. this._options = options;
  62001. if (!this._isMainTrack) {
  62002. this._scene.soundTracks.push(this);
  62003. this.id = this._scene.soundTracks.length - 1;
  62004. }
  62005. }
  62006. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62007. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62008. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62009. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62010. if (this._options) {
  62011. if (this._options.volume) {
  62012. this._outputAudioNode.gain.value = this._options.volume;
  62013. }
  62014. if (this._options.mainTrack) {
  62015. this._isMainTrack = this._options.mainTrack;
  62016. }
  62017. }
  62018. this._isInitialized = true;
  62019. }
  62020. };
  62021. SoundTrack.prototype.dispose = function () {
  62022. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62023. if (this._connectedAnalyser) {
  62024. this._connectedAnalyser.stopDebugCanvas();
  62025. }
  62026. while (this.soundCollection.length) {
  62027. this.soundCollection[0].dispose();
  62028. }
  62029. if (this._outputAudioNode) {
  62030. this._outputAudioNode.disconnect();
  62031. }
  62032. this._outputAudioNode = null;
  62033. }
  62034. };
  62035. SoundTrack.prototype.AddSound = function (sound) {
  62036. if (!this._isInitialized) {
  62037. this._initializeSoundTrackAudioGraph();
  62038. }
  62039. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62040. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62041. }
  62042. if (sound.soundTrackId) {
  62043. if (sound.soundTrackId === -1) {
  62044. this._scene.mainSoundTrack.RemoveSound(sound);
  62045. }
  62046. else {
  62047. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62048. }
  62049. }
  62050. this.soundCollection.push(sound);
  62051. sound.soundTrackId = this.id;
  62052. };
  62053. SoundTrack.prototype.RemoveSound = function (sound) {
  62054. var index = this.soundCollection.indexOf(sound);
  62055. if (index !== -1) {
  62056. this.soundCollection.splice(index, 1);
  62057. }
  62058. };
  62059. SoundTrack.prototype.setVolume = function (newVolume) {
  62060. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62061. this._outputAudioNode.gain.value = newVolume;
  62062. }
  62063. };
  62064. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62065. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62066. for (var i = 0; i < this.soundCollection.length; i++) {
  62067. this.soundCollection[i].switchPanningModelToHRTF();
  62068. }
  62069. }
  62070. };
  62071. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62072. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62073. for (var i = 0; i < this.soundCollection.length; i++) {
  62074. this.soundCollection[i].switchPanningModelToEqualPower();
  62075. }
  62076. }
  62077. };
  62078. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62079. if (this._connectedAnalyser) {
  62080. this._connectedAnalyser.stopDebugCanvas();
  62081. }
  62082. this._connectedAnalyser = analyser;
  62083. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62084. this._outputAudioNode.disconnect();
  62085. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62086. }
  62087. };
  62088. return SoundTrack;
  62089. }());
  62090. BABYLON.SoundTrack = SoundTrack;
  62091. })(BABYLON || (BABYLON = {}));
  62092. //# sourceMappingURL=babylon.soundtrack.js.map
  62093. var BABYLON;
  62094. (function (BABYLON) {
  62095. /**
  62096. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62097. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62098. */
  62099. var Analyser = /** @class */ (function () {
  62100. /**
  62101. * Creates a new analyser
  62102. * @param scene defines hosting scene
  62103. */
  62104. function Analyser(scene) {
  62105. /**
  62106. * Gets or sets the smoothing
  62107. * @ignorenaming
  62108. */
  62109. this.SMOOTHING = 0.75;
  62110. /**
  62111. * Gets or sets the FFT table size
  62112. * @ignorenaming
  62113. */
  62114. this.FFT_SIZE = 512;
  62115. /**
  62116. * Gets or sets the bar graph amplitude
  62117. * @ignorenaming
  62118. */
  62119. this.BARGRAPHAMPLITUDE = 256;
  62120. /**
  62121. * Gets or sets the position of the debug canvas
  62122. * @ignorenaming
  62123. */
  62124. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62125. /**
  62126. * Gets or sets the debug canvas size
  62127. * @ignorenaming
  62128. */
  62129. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62130. this._scene = scene;
  62131. this._audioEngine = BABYLON.Engine.audioEngine;
  62132. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62133. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62134. this._webAudioAnalyser.minDecibels = -140;
  62135. this._webAudioAnalyser.maxDecibels = 0;
  62136. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62137. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62138. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62139. }
  62140. }
  62141. /**
  62142. * Get the number of data values you will have to play with for the visualization
  62143. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62144. * @returns a number
  62145. */
  62146. Analyser.prototype.getFrequencyBinCount = function () {
  62147. if (this._audioEngine.canUseWebAudio) {
  62148. return this._webAudioAnalyser.frequencyBinCount;
  62149. }
  62150. else {
  62151. return 0;
  62152. }
  62153. };
  62154. /**
  62155. * Gets the current frequency data as a byte array
  62156. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62157. * @returns a Uint8Array
  62158. */
  62159. Analyser.prototype.getByteFrequencyData = function () {
  62160. if (this._audioEngine.canUseWebAudio) {
  62161. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62162. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62163. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62164. }
  62165. return this._byteFreqs;
  62166. };
  62167. /**
  62168. * Gets the current waveform as a byte array
  62169. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62170. * @returns a Uint8Array
  62171. */
  62172. Analyser.prototype.getByteTimeDomainData = function () {
  62173. if (this._audioEngine.canUseWebAudio) {
  62174. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62175. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62176. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62177. }
  62178. return this._byteTime;
  62179. };
  62180. /**
  62181. * Gets the current frequency data as a float array
  62182. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62183. * @returns a Float32Array
  62184. */
  62185. Analyser.prototype.getFloatFrequencyData = function () {
  62186. if (this._audioEngine.canUseWebAudio) {
  62187. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62188. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62189. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62190. }
  62191. return this._floatFreqs;
  62192. };
  62193. /**
  62194. * Renders the debug canvas
  62195. */
  62196. Analyser.prototype.drawDebugCanvas = function () {
  62197. var _this = this;
  62198. if (this._audioEngine.canUseWebAudio) {
  62199. if (!this._debugCanvas) {
  62200. this._debugCanvas = document.createElement("canvas");
  62201. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62202. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62203. this._debugCanvas.style.position = "absolute";
  62204. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62205. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62206. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62207. document.body.appendChild(this._debugCanvas);
  62208. this._registerFunc = function () {
  62209. _this.drawDebugCanvas();
  62210. };
  62211. this._scene.registerBeforeRender(this._registerFunc);
  62212. }
  62213. if (this._registerFunc && this._debugCanvasContext) {
  62214. var workingArray = this.getByteFrequencyData();
  62215. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62216. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62217. // Draw the frequency domain chart.
  62218. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62219. var value = workingArray[i];
  62220. var percent = value / this.BARGRAPHAMPLITUDE;
  62221. var height = this.DEBUGCANVASSIZE.height * percent;
  62222. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62223. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62224. var hue = i / this.getFrequencyBinCount() * 360;
  62225. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62226. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62227. }
  62228. }
  62229. }
  62230. };
  62231. /**
  62232. * Stops rendering the debug canvas and removes it
  62233. */
  62234. Analyser.prototype.stopDebugCanvas = function () {
  62235. if (this._debugCanvas) {
  62236. if (this._registerFunc) {
  62237. this._scene.unregisterBeforeRender(this._registerFunc);
  62238. this._registerFunc = null;
  62239. }
  62240. document.body.removeChild(this._debugCanvas);
  62241. this._debugCanvas = null;
  62242. this._debugCanvasContext = null;
  62243. }
  62244. };
  62245. /**
  62246. * Connects two audio nodes
  62247. * @param inputAudioNode defines first node to connect
  62248. * @param outputAudioNode defines second node to connect
  62249. */
  62250. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62251. if (this._audioEngine.canUseWebAudio) {
  62252. inputAudioNode.connect(this._webAudioAnalyser);
  62253. this._webAudioAnalyser.connect(outputAudioNode);
  62254. }
  62255. };
  62256. /**
  62257. * Releases all associated resources
  62258. */
  62259. Analyser.prototype.dispose = function () {
  62260. if (this._audioEngine.canUseWebAudio) {
  62261. this._webAudioAnalyser.disconnect();
  62262. }
  62263. };
  62264. return Analyser;
  62265. }());
  62266. BABYLON.Analyser = Analyser;
  62267. })(BABYLON || (BABYLON = {}));
  62268. //# sourceMappingURL=babylon.analyser.js.map
  62269. var BABYLON;
  62270. (function (BABYLON) {
  62271. var CubeTexture = /** @class */ (function (_super) {
  62272. __extends(CubeTexture, _super);
  62273. /**
  62274. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  62275. * as prefiltered data.
  62276. * @param rootUrl defines the url of the texture or the root name of the six images
  62277. * @param scene defines the scene the texture is attached to
  62278. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  62279. * @param noMipmap defines if mipmaps should be created or not
  62280. * @param files defines the six files to load for the different faces
  62281. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  62282. * @param onError defines a callback triggered in case of error during load
  62283. * @param format defines the internal format to use for the texture once loaded
  62284. * @param prefiltered defines whether or not the texture is created from prefiltered data
  62285. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  62286. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62287. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  62288. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  62289. * @return the cube texture
  62290. */
  62291. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  62292. if (extensions === void 0) { extensions = null; }
  62293. if (noMipmap === void 0) { noMipmap = false; }
  62294. if (files === void 0) { files = null; }
  62295. if (onLoad === void 0) { onLoad = null; }
  62296. if (onError === void 0) { onError = null; }
  62297. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62298. if (prefiltered === void 0) { prefiltered = false; }
  62299. if (forcedExtension === void 0) { forcedExtension = null; }
  62300. if (createPolynomials === void 0) { createPolynomials = false; }
  62301. if (lodScale === void 0) { lodScale = 0.8; }
  62302. if (lodOffset === void 0) { lodOffset = 0; }
  62303. var _this = _super.call(this, scene) || this;
  62304. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62305. /**
  62306. * Gets or sets the center of the bounding box associated with the cube texture
  62307. * It must define where the camera used to render the texture was set
  62308. */
  62309. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62310. _this._rotationY = 0;
  62311. /** @hidden */
  62312. _this._prefiltered = false;
  62313. _this.name = rootUrl;
  62314. _this.url = rootUrl;
  62315. _this._noMipmap = noMipmap;
  62316. _this.hasAlpha = false;
  62317. _this._format = format;
  62318. _this.isCube = true;
  62319. _this._textureMatrix = BABYLON.Matrix.Identity();
  62320. _this._createPolynomials = createPolynomials;
  62321. if (!rootUrl && !files) {
  62322. return _this;
  62323. }
  62324. var lastDot = rootUrl.lastIndexOf(".");
  62325. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62326. var isDDS = (extension === ".dds");
  62327. var isEnv = (extension === ".env");
  62328. if (isEnv) {
  62329. _this.gammaSpace = false;
  62330. _this._prefiltered = false;
  62331. }
  62332. else {
  62333. _this._prefiltered = prefiltered;
  62334. if (prefiltered) {
  62335. _this.gammaSpace = false;
  62336. }
  62337. }
  62338. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62339. if (!files) {
  62340. if (!isEnv && !isDDS && !extensions) {
  62341. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62342. }
  62343. files = [];
  62344. if (extensions) {
  62345. for (var index = 0; index < extensions.length; index++) {
  62346. files.push(rootUrl + extensions[index]);
  62347. }
  62348. }
  62349. }
  62350. _this._files = files;
  62351. if (!_this._texture) {
  62352. if (!scene.useDelayedTextureLoading) {
  62353. if (prefiltered) {
  62354. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  62355. }
  62356. else {
  62357. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  62358. }
  62359. }
  62360. else {
  62361. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62362. }
  62363. }
  62364. else if (onLoad) {
  62365. if (_this._texture.isReady) {
  62366. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62367. }
  62368. else {
  62369. _this._texture.onLoadedObservable.add(onLoad);
  62370. }
  62371. }
  62372. return _this;
  62373. }
  62374. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62375. get: function () {
  62376. return this._boundingBoxSize;
  62377. },
  62378. /**
  62379. * Gets or sets the size of the bounding box associated with the cube texture
  62380. * When defined, the cubemap will switch to local mode
  62381. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62382. * @example https://www.babylonjs-playground.com/#RNASML
  62383. */
  62384. set: function (value) {
  62385. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62386. return;
  62387. }
  62388. this._boundingBoxSize = value;
  62389. var scene = this.getScene();
  62390. if (scene) {
  62391. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62392. }
  62393. },
  62394. enumerable: true,
  62395. configurable: true
  62396. });
  62397. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62398. /**
  62399. * Gets texture matrix rotation angle around Y axis radians.
  62400. */
  62401. get: function () {
  62402. return this._rotationY;
  62403. },
  62404. /**
  62405. * Sets texture matrix rotation angle around Y axis in radians.
  62406. */
  62407. set: function (value) {
  62408. this._rotationY = value;
  62409. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62410. },
  62411. enumerable: true,
  62412. configurable: true
  62413. });
  62414. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62415. var rootUrlKey = "";
  62416. files.forEach(function (url) { return rootUrlKey += url; });
  62417. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62418. };
  62419. /**
  62420. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  62421. * @param url defines the url of the prefiltered texture
  62422. * @param scene defines the scene the texture is attached to
  62423. * @param forcedExtension defines the extension of the file if different from the url
  62424. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62425. * @return the prefiltered texture
  62426. */
  62427. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  62428. if (forcedExtension === void 0) { forcedExtension = null; }
  62429. if (createPolynomials === void 0) { createPolynomials = true; }
  62430. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  62431. };
  62432. // Methods
  62433. CubeTexture.prototype.delayLoad = function () {
  62434. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62435. return;
  62436. }
  62437. var scene = this.getScene();
  62438. if (!scene) {
  62439. return;
  62440. }
  62441. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62442. this._texture = this._getFromCache(this.url, this._noMipmap);
  62443. if (!this._texture) {
  62444. if (this._prefiltered) {
  62445. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  62446. }
  62447. else {
  62448. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62449. }
  62450. }
  62451. };
  62452. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62453. return this._textureMatrix;
  62454. };
  62455. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62456. this._textureMatrix = value;
  62457. };
  62458. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62459. var texture = BABYLON.SerializationHelper.Parse(function () {
  62460. var prefiltered = false;
  62461. if (parsedTexture.prefiltered) {
  62462. prefiltered = parsedTexture.prefiltered;
  62463. }
  62464. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  62465. }, parsedTexture, scene);
  62466. // Local Cubemaps
  62467. if (parsedTexture.boundingBoxPosition) {
  62468. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62469. }
  62470. if (parsedTexture.boundingBoxSize) {
  62471. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62472. }
  62473. // Animations
  62474. if (parsedTexture.animations) {
  62475. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62476. var parsedAnimation = parsedTexture.animations[animationIndex];
  62477. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62478. }
  62479. }
  62480. return texture;
  62481. };
  62482. CubeTexture.prototype.clone = function () {
  62483. var _this = this;
  62484. return BABYLON.SerializationHelper.Clone(function () {
  62485. var scene = _this.getScene();
  62486. if (!scene) {
  62487. return _this;
  62488. }
  62489. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62490. }, this);
  62491. };
  62492. __decorate([
  62493. BABYLON.serialize("rotationY")
  62494. ], CubeTexture.prototype, "_rotationY", void 0);
  62495. return CubeTexture;
  62496. }(BABYLON.BaseTexture));
  62497. BABYLON.CubeTexture = CubeTexture;
  62498. })(BABYLON || (BABYLON = {}));
  62499. //# sourceMappingURL=babylon.cubeTexture.js.map
  62500. var BABYLON;
  62501. (function (BABYLON) {
  62502. var RenderTargetTexture = /** @class */ (function (_super) {
  62503. __extends(RenderTargetTexture, _super);
  62504. /**
  62505. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62506. * or used a shadow, depth texture...
  62507. * @param name The friendly name of the texture
  62508. * @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)
  62509. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62510. * @param generateMipMaps True if mip maps need to be generated after render.
  62511. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62512. * @param type The type of the buffer in the RTT (int, half float, float...)
  62513. * @param isCube True if a cube texture needs to be created
  62514. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62515. * @param generateDepthBuffer True to generate a depth buffer
  62516. * @param generateStencilBuffer True to generate a stencil buffer
  62517. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62518. */
  62519. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62520. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62521. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62522. if (isCube === void 0) { isCube = false; }
  62523. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62524. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62525. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62526. if (isMulti === void 0) { isMulti = false; }
  62527. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62528. _this.isCube = isCube;
  62529. /**
  62530. * Use this list to define the list of mesh you want to render.
  62531. */
  62532. _this.renderList = new Array();
  62533. _this.renderParticles = true;
  62534. _this.renderSprites = false;
  62535. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62536. _this.ignoreCameraViewport = false;
  62537. // Events
  62538. /**
  62539. * An event triggered when the texture is unbind.
  62540. */
  62541. _this.onBeforeBindObservable = new BABYLON.Observable();
  62542. /**
  62543. * An event triggered when the texture is unbind.
  62544. */
  62545. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62546. /**
  62547. * An event triggered before rendering the texture
  62548. */
  62549. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62550. /**
  62551. * An event triggered after rendering the texture
  62552. */
  62553. _this.onAfterRenderObservable = new BABYLON.Observable();
  62554. /**
  62555. * An event triggered after the texture clear
  62556. */
  62557. _this.onClearObservable = new BABYLON.Observable();
  62558. _this._currentRefreshId = -1;
  62559. _this._refreshRate = 1;
  62560. _this._samples = 1;
  62561. /**
  62562. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62563. * It must define where the camera used to render the texture is set
  62564. */
  62565. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62566. scene = _this.getScene();
  62567. if (!scene) {
  62568. return _this;
  62569. }
  62570. _this._engine = scene.getEngine();
  62571. _this.name = name;
  62572. _this.isRenderTarget = true;
  62573. _this._initialSizeParameter = size;
  62574. _this._processSizeParameter(size);
  62575. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62576. });
  62577. _this._generateMipMaps = generateMipMaps ? true : false;
  62578. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62579. // Rendering groups
  62580. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62581. if (isMulti) {
  62582. return _this;
  62583. }
  62584. _this._renderTargetOptions = {
  62585. generateMipMaps: generateMipMaps,
  62586. type: type,
  62587. samplingMode: samplingMode,
  62588. generateDepthBuffer: generateDepthBuffer,
  62589. generateStencilBuffer: generateStencilBuffer
  62590. };
  62591. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62592. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62593. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62594. }
  62595. if (isCube) {
  62596. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62597. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62598. _this._textureMatrix = BABYLON.Matrix.Identity();
  62599. }
  62600. else {
  62601. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62602. }
  62603. return _this;
  62604. }
  62605. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62606. get: function () {
  62607. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62608. },
  62609. enumerable: true,
  62610. configurable: true
  62611. });
  62612. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62613. get: function () {
  62614. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62615. },
  62616. enumerable: true,
  62617. configurable: true
  62618. });
  62619. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62620. get: function () {
  62621. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62622. },
  62623. enumerable: true,
  62624. configurable: true
  62625. });
  62626. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62627. set: function (callback) {
  62628. if (this._onAfterUnbindObserver) {
  62629. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62630. }
  62631. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62632. },
  62633. enumerable: true,
  62634. configurable: true
  62635. });
  62636. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62637. set: function (callback) {
  62638. if (this._onBeforeRenderObserver) {
  62639. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62640. }
  62641. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62642. },
  62643. enumerable: true,
  62644. configurable: true
  62645. });
  62646. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62647. set: function (callback) {
  62648. if (this._onAfterRenderObserver) {
  62649. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62650. }
  62651. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62652. },
  62653. enumerable: true,
  62654. configurable: true
  62655. });
  62656. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62657. set: function (callback) {
  62658. if (this._onClearObserver) {
  62659. this.onClearObservable.remove(this._onClearObserver);
  62660. }
  62661. this._onClearObserver = this.onClearObservable.add(callback);
  62662. },
  62663. enumerable: true,
  62664. configurable: true
  62665. });
  62666. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62667. get: function () {
  62668. return this._renderTargetOptions;
  62669. },
  62670. enumerable: true,
  62671. configurable: true
  62672. });
  62673. RenderTargetTexture.prototype._onRatioRescale = function () {
  62674. if (this._sizeRatio) {
  62675. this.resize(this._initialSizeParameter);
  62676. }
  62677. };
  62678. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62679. get: function () {
  62680. return this._boundingBoxSize;
  62681. },
  62682. /**
  62683. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62684. * When defined, the cubemap will switch to local mode
  62685. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62686. * @example https://www.babylonjs-playground.com/#RNASML
  62687. */
  62688. set: function (value) {
  62689. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62690. return;
  62691. }
  62692. this._boundingBoxSize = value;
  62693. var scene = this.getScene();
  62694. if (scene) {
  62695. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62696. }
  62697. },
  62698. enumerable: true,
  62699. configurable: true
  62700. });
  62701. /**
  62702. * Creates a depth stencil texture.
  62703. * This is only available in WebGL 2 or with the depth texture extension available.
  62704. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62705. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62706. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62707. */
  62708. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62709. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62710. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62711. if (generateStencil === void 0) { generateStencil = false; }
  62712. if (!this.getScene()) {
  62713. return;
  62714. }
  62715. var engine = this.getScene().getEngine();
  62716. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62717. bilinearFiltering: bilinearFiltering,
  62718. comparisonFunction: comparisonFunction,
  62719. generateStencil: generateStencil,
  62720. isCube: this.isCube
  62721. });
  62722. engine.setFrameBufferDepthStencilTexture(this);
  62723. };
  62724. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62725. if (size.ratio) {
  62726. this._sizeRatio = size.ratio;
  62727. this._size = {
  62728. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62729. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62730. };
  62731. }
  62732. else {
  62733. this._size = size;
  62734. }
  62735. };
  62736. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62737. get: function () {
  62738. return this._samples;
  62739. },
  62740. set: function (value) {
  62741. if (this._samples === value) {
  62742. return;
  62743. }
  62744. var scene = this.getScene();
  62745. if (!scene) {
  62746. return;
  62747. }
  62748. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62749. },
  62750. enumerable: true,
  62751. configurable: true
  62752. });
  62753. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62754. this._currentRefreshId = -1;
  62755. };
  62756. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62757. get: function () {
  62758. return this._refreshRate;
  62759. },
  62760. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62761. set: function (value) {
  62762. this._refreshRate = value;
  62763. this.resetRefreshCounter();
  62764. },
  62765. enumerable: true,
  62766. configurable: true
  62767. });
  62768. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62769. if (!this._postProcessManager) {
  62770. var scene = this.getScene();
  62771. if (!scene) {
  62772. return;
  62773. }
  62774. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62775. this._postProcesses = new Array();
  62776. }
  62777. this._postProcesses.push(postProcess);
  62778. this._postProcesses[0].autoClear = false;
  62779. };
  62780. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62781. if (!this._postProcesses) {
  62782. return;
  62783. }
  62784. if (dispose) {
  62785. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62786. var postProcess = _a[_i];
  62787. postProcess.dispose();
  62788. }
  62789. }
  62790. this._postProcesses = [];
  62791. };
  62792. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62793. if (!this._postProcesses) {
  62794. return;
  62795. }
  62796. var index = this._postProcesses.indexOf(postProcess);
  62797. if (index === -1) {
  62798. return;
  62799. }
  62800. this._postProcesses.splice(index, 1);
  62801. if (this._postProcesses.length > 0) {
  62802. this._postProcesses[0].autoClear = false;
  62803. }
  62804. };
  62805. RenderTargetTexture.prototype._shouldRender = function () {
  62806. if (this._currentRefreshId === -1) { // At least render once
  62807. this._currentRefreshId = 1;
  62808. return true;
  62809. }
  62810. if (this.refreshRate === this._currentRefreshId) {
  62811. this._currentRefreshId = 1;
  62812. return true;
  62813. }
  62814. this._currentRefreshId++;
  62815. return false;
  62816. };
  62817. RenderTargetTexture.prototype.getRenderSize = function () {
  62818. if (this._size.width) {
  62819. return this._size.width;
  62820. }
  62821. return this._size;
  62822. };
  62823. RenderTargetTexture.prototype.getRenderWidth = function () {
  62824. if (this._size.width) {
  62825. return this._size.width;
  62826. }
  62827. return this._size;
  62828. };
  62829. RenderTargetTexture.prototype.getRenderHeight = function () {
  62830. if (this._size.width) {
  62831. return this._size.height;
  62832. }
  62833. return this._size;
  62834. };
  62835. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62836. get: function () {
  62837. return true;
  62838. },
  62839. enumerable: true,
  62840. configurable: true
  62841. });
  62842. RenderTargetTexture.prototype.scale = function (ratio) {
  62843. var newSize = this.getRenderSize() * ratio;
  62844. this.resize(newSize);
  62845. };
  62846. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62847. if (this.isCube) {
  62848. return this._textureMatrix;
  62849. }
  62850. return _super.prototype.getReflectionTextureMatrix.call(this);
  62851. };
  62852. RenderTargetTexture.prototype.resize = function (size) {
  62853. this.releaseInternalTexture();
  62854. var scene = this.getScene();
  62855. if (!scene) {
  62856. return;
  62857. }
  62858. this._processSizeParameter(size);
  62859. if (this.isCube) {
  62860. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62861. }
  62862. else {
  62863. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62864. }
  62865. };
  62866. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62867. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62868. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62869. var scene = this.getScene();
  62870. if (!scene) {
  62871. return;
  62872. }
  62873. var engine = scene.getEngine();
  62874. if (this.useCameraPostProcesses !== undefined) {
  62875. useCameraPostProcess = this.useCameraPostProcesses;
  62876. }
  62877. if (this._waitingRenderList) {
  62878. this.renderList = [];
  62879. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62880. var id = this._waitingRenderList[index];
  62881. var mesh_1 = scene.getMeshByID(id);
  62882. if (mesh_1) {
  62883. this.renderList.push(mesh_1);
  62884. }
  62885. }
  62886. delete this._waitingRenderList;
  62887. }
  62888. // Is predicate defined?
  62889. if (this.renderListPredicate) {
  62890. if (this.renderList) {
  62891. this.renderList.splice(0); // Clear previous renderList
  62892. }
  62893. else {
  62894. this.renderList = [];
  62895. }
  62896. var scene = this.getScene();
  62897. if (!scene) {
  62898. return;
  62899. }
  62900. var sceneMeshes = scene.meshes;
  62901. for (var index = 0; index < sceneMeshes.length; index++) {
  62902. var mesh = sceneMeshes[index];
  62903. if (this.renderListPredicate(mesh)) {
  62904. this.renderList.push(mesh);
  62905. }
  62906. }
  62907. }
  62908. this.onBeforeBindObservable.notifyObservers(this);
  62909. // Set custom projection.
  62910. // Needs to be before binding to prevent changing the aspect ratio.
  62911. var camera;
  62912. if (this.activeCamera) {
  62913. camera = this.activeCamera;
  62914. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62915. if (this.activeCamera !== scene.activeCamera) {
  62916. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  62917. }
  62918. }
  62919. else {
  62920. camera = scene.activeCamera;
  62921. if (camera) {
  62922. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62923. }
  62924. }
  62925. // Prepare renderingManager
  62926. this._renderingManager.reset();
  62927. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  62928. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  62929. var sceneRenderId = scene.getRenderId();
  62930. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  62931. var mesh = currentRenderList[meshIndex];
  62932. if (mesh) {
  62933. if (!mesh.isReady(this.refreshRate === 0)) {
  62934. this.resetRefreshCounter();
  62935. continue;
  62936. }
  62937. mesh._preActivateForIntermediateRendering(sceneRenderId);
  62938. var isMasked = void 0;
  62939. if (!this.renderList && camera) {
  62940. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  62941. }
  62942. else {
  62943. isMasked = false;
  62944. }
  62945. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  62946. mesh._activate(sceneRenderId);
  62947. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  62948. var subMesh = mesh.subMeshes[subIndex];
  62949. scene._activeIndices.addCount(subMesh.indexCount, false);
  62950. this._renderingManager.dispatch(subMesh, mesh);
  62951. }
  62952. }
  62953. }
  62954. }
  62955. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  62956. var particleSystem = scene.particleSystems[particleIndex];
  62957. var emitter = particleSystem.emitter;
  62958. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  62959. continue;
  62960. }
  62961. if (currentRenderList.indexOf(emitter) >= 0) {
  62962. this._renderingManager.dispatchParticles(particleSystem);
  62963. }
  62964. }
  62965. if (this.isCube) {
  62966. for (var face = 0; face < 6; face++) {
  62967. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62968. scene.incrementRenderId();
  62969. scene.resetCachedMaterial();
  62970. }
  62971. }
  62972. else {
  62973. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62974. }
  62975. this.onAfterUnbindObservable.notifyObservers(this);
  62976. if (scene.activeCamera) {
  62977. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  62978. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  62979. }
  62980. engine.setViewport(scene.activeCamera.viewport);
  62981. }
  62982. scene.resetCachedMaterial();
  62983. };
  62984. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  62985. var minimum = 128;
  62986. var x = renderDimension * scale;
  62987. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  62988. // Ensure we don't exceed the render dimension (while staying POT)
  62989. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  62990. };
  62991. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62992. var _this = this;
  62993. if (!this._texture) {
  62994. return;
  62995. }
  62996. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  62997. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62998. });
  62999. };
  63000. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63001. var scene = this.getScene();
  63002. if (!scene) {
  63003. return;
  63004. }
  63005. var engine = scene.getEngine();
  63006. if (!this._texture) {
  63007. return;
  63008. }
  63009. // Bind
  63010. if (this._postProcessManager) {
  63011. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63012. }
  63013. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63014. if (this._texture) {
  63015. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63016. }
  63017. }
  63018. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63019. // Clear
  63020. if (this.onClearObservable.hasObservers()) {
  63021. this.onClearObservable.notifyObservers(engine);
  63022. }
  63023. else {
  63024. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63025. }
  63026. if (!this._doNotChangeAspectRatio) {
  63027. scene.updateTransformMatrix(true);
  63028. }
  63029. // Render
  63030. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63031. if (this._postProcessManager) {
  63032. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63033. }
  63034. else if (useCameraPostProcess) {
  63035. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63036. }
  63037. if (!this._doNotChangeAspectRatio) {
  63038. scene.updateTransformMatrix(true);
  63039. }
  63040. // Dump ?
  63041. if (dumpForDebug) {
  63042. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63043. }
  63044. // Unbind
  63045. if (!this.isCube || faceIndex === 5) {
  63046. if (this.isCube) {
  63047. if (faceIndex === 5) {
  63048. engine.generateMipMapsForCubemap(this._texture);
  63049. }
  63050. }
  63051. this.unbindFrameBuffer(engine, faceIndex);
  63052. }
  63053. else {
  63054. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63055. }
  63056. };
  63057. /**
  63058. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63059. * This allowed control for front to back rendering or reversly depending of the special needs.
  63060. *
  63061. * @param renderingGroupId The rendering group id corresponding to its index
  63062. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63063. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63064. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63065. */
  63066. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63067. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63068. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63069. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63070. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63071. };
  63072. /**
  63073. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63074. *
  63075. * @param renderingGroupId The rendering group id corresponding to its index
  63076. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63077. */
  63078. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63079. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63080. };
  63081. RenderTargetTexture.prototype.clone = function () {
  63082. var textureSize = this.getSize();
  63083. 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);
  63084. // Base texture
  63085. newTexture.hasAlpha = this.hasAlpha;
  63086. newTexture.level = this.level;
  63087. // RenderTarget Texture
  63088. newTexture.coordinatesMode = this.coordinatesMode;
  63089. if (this.renderList) {
  63090. newTexture.renderList = this.renderList.slice(0);
  63091. }
  63092. return newTexture;
  63093. };
  63094. RenderTargetTexture.prototype.serialize = function () {
  63095. if (!this.name) {
  63096. return null;
  63097. }
  63098. var serializationObject = _super.prototype.serialize.call(this);
  63099. serializationObject.renderTargetSize = this.getRenderSize();
  63100. serializationObject.renderList = [];
  63101. if (this.renderList) {
  63102. for (var index = 0; index < this.renderList.length; index++) {
  63103. serializationObject.renderList.push(this.renderList[index].id);
  63104. }
  63105. }
  63106. return serializationObject;
  63107. };
  63108. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63109. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63110. var objBuffer = this.getInternalTexture();
  63111. var scene = this.getScene();
  63112. if (objBuffer && scene) {
  63113. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63114. }
  63115. };
  63116. RenderTargetTexture.prototype.dispose = function () {
  63117. if (this._postProcessManager) {
  63118. this._postProcessManager.dispose();
  63119. this._postProcessManager = null;
  63120. }
  63121. this.clearPostProcesses(true);
  63122. if (this._resizeObserver) {
  63123. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63124. this._resizeObserver = null;
  63125. }
  63126. this.renderList = null;
  63127. // Remove from custom render targets
  63128. var scene = this.getScene();
  63129. if (!scene) {
  63130. return;
  63131. }
  63132. var index = scene.customRenderTargets.indexOf(this);
  63133. if (index >= 0) {
  63134. scene.customRenderTargets.splice(index, 1);
  63135. }
  63136. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63137. var camera = _a[_i];
  63138. index = camera.customRenderTargets.indexOf(this);
  63139. if (index >= 0) {
  63140. camera.customRenderTargets.splice(index, 1);
  63141. }
  63142. }
  63143. _super.prototype.dispose.call(this);
  63144. };
  63145. RenderTargetTexture.prototype._rebuild = function () {
  63146. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63147. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63148. }
  63149. if (this._postProcessManager) {
  63150. this._postProcessManager._rebuild();
  63151. }
  63152. };
  63153. /**
  63154. * Clear the info related to rendering groups preventing retention point in material dispose.
  63155. */
  63156. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63157. if (this._renderingManager) {
  63158. this._renderingManager.freeRenderingGroups();
  63159. }
  63160. };
  63161. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63162. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63163. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63164. return RenderTargetTexture;
  63165. }(BABYLON.Texture));
  63166. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63167. })(BABYLON || (BABYLON = {}));
  63168. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63169. var BABYLON;
  63170. (function (BABYLON) {
  63171. ;
  63172. var MultiRenderTarget = /** @class */ (function (_super) {
  63173. __extends(MultiRenderTarget, _super);
  63174. function MultiRenderTarget(name, size, count, scene, options) {
  63175. var _this = this;
  63176. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63177. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63178. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63179. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63180. _this._engine = scene.getEngine();
  63181. if (!_this.isSupported) {
  63182. _this.dispose();
  63183. return;
  63184. }
  63185. var types = [];
  63186. var samplingModes = [];
  63187. for (var i = 0; i < count; i++) {
  63188. if (options && options.types && options.types[i] !== undefined) {
  63189. types.push(options.types[i]);
  63190. }
  63191. else {
  63192. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63193. }
  63194. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63195. samplingModes.push(options.samplingModes[i]);
  63196. }
  63197. else {
  63198. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63199. }
  63200. }
  63201. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63202. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63203. _this._size = size;
  63204. _this._multiRenderTargetOptions = {
  63205. samplingModes: samplingModes,
  63206. generateMipMaps: generateMipMaps,
  63207. generateDepthBuffer: generateDepthBuffer,
  63208. generateStencilBuffer: generateStencilBuffer,
  63209. generateDepthTexture: generateDepthTexture,
  63210. types: types,
  63211. textureCount: count
  63212. };
  63213. _this._createInternalTextures();
  63214. _this._createTextures();
  63215. return _this;
  63216. }
  63217. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63218. get: function () {
  63219. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63220. },
  63221. enumerable: true,
  63222. configurable: true
  63223. });
  63224. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63225. get: function () {
  63226. return this._textures;
  63227. },
  63228. enumerable: true,
  63229. configurable: true
  63230. });
  63231. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63232. get: function () {
  63233. return this._textures[this._textures.length - 1];
  63234. },
  63235. enumerable: true,
  63236. configurable: true
  63237. });
  63238. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63239. set: function (wrap) {
  63240. if (this._textures) {
  63241. for (var i = 0; i < this._textures.length; i++) {
  63242. this._textures[i].wrapU = wrap;
  63243. }
  63244. }
  63245. },
  63246. enumerable: true,
  63247. configurable: true
  63248. });
  63249. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63250. set: function (wrap) {
  63251. if (this._textures) {
  63252. for (var i = 0; i < this._textures.length; i++) {
  63253. this._textures[i].wrapV = wrap;
  63254. }
  63255. }
  63256. },
  63257. enumerable: true,
  63258. configurable: true
  63259. });
  63260. MultiRenderTarget.prototype._rebuild = function () {
  63261. this.releaseInternalTextures();
  63262. this._createInternalTextures();
  63263. for (var i = 0; i < this._internalTextures.length; i++) {
  63264. var texture = this._textures[i];
  63265. texture._texture = this._internalTextures[i];
  63266. }
  63267. // Keeps references to frame buffer and stencil/depth buffer
  63268. this._texture = this._internalTextures[0];
  63269. };
  63270. MultiRenderTarget.prototype._createInternalTextures = function () {
  63271. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63272. };
  63273. MultiRenderTarget.prototype._createTextures = function () {
  63274. this._textures = [];
  63275. for (var i = 0; i < this._internalTextures.length; i++) {
  63276. var texture = new BABYLON.Texture(null, this.getScene());
  63277. texture._texture = this._internalTextures[i];
  63278. this._textures.push(texture);
  63279. }
  63280. // Keeps references to frame buffer and stencil/depth buffer
  63281. this._texture = this._internalTextures[0];
  63282. };
  63283. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63284. get: function () {
  63285. return this._samples;
  63286. },
  63287. set: function (value) {
  63288. if (this._samples === value) {
  63289. return;
  63290. }
  63291. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63292. },
  63293. enumerable: true,
  63294. configurable: true
  63295. });
  63296. MultiRenderTarget.prototype.resize = function (size) {
  63297. this.releaseInternalTextures();
  63298. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63299. this._createInternalTextures();
  63300. };
  63301. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63302. var _this = this;
  63303. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63304. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63305. });
  63306. };
  63307. MultiRenderTarget.prototype.dispose = function () {
  63308. this.releaseInternalTextures();
  63309. _super.prototype.dispose.call(this);
  63310. };
  63311. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63312. if (!this._internalTextures) {
  63313. return;
  63314. }
  63315. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63316. if (this._internalTextures[i] !== undefined) {
  63317. this._internalTextures[i].dispose();
  63318. this._internalTextures.splice(i, 1);
  63319. }
  63320. }
  63321. };
  63322. return MultiRenderTarget;
  63323. }(BABYLON.RenderTargetTexture));
  63324. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63325. })(BABYLON || (BABYLON = {}));
  63326. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63327. var BABYLON;
  63328. (function (BABYLON) {
  63329. var MirrorTexture = /** @class */ (function (_super) {
  63330. __extends(MirrorTexture, _super);
  63331. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63332. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63333. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63334. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63335. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63336. _this.scene = scene;
  63337. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63338. _this._transformMatrix = BABYLON.Matrix.Zero();
  63339. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63340. _this._adaptiveBlurKernel = 0;
  63341. _this._blurKernelX = 0;
  63342. _this._blurKernelY = 0;
  63343. _this._blurRatio = 1.0;
  63344. _this.ignoreCameraViewport = true;
  63345. _this._updateGammaSpace();
  63346. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63347. _this._updateGammaSpace;
  63348. });
  63349. _this.onBeforeRenderObservable.add(function () {
  63350. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63351. _this._savedViewMatrix = scene.getViewMatrix();
  63352. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63353. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63354. scene.clipPlane = _this.mirrorPlane;
  63355. scene.getEngine().cullBackFaces = false;
  63356. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63357. });
  63358. _this.onAfterRenderObservable.add(function () {
  63359. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63360. scene.getEngine().cullBackFaces = true;
  63361. scene._mirroredCameraPosition = null;
  63362. delete scene.clipPlane;
  63363. });
  63364. return _this;
  63365. }
  63366. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63367. get: function () {
  63368. return this._blurRatio;
  63369. },
  63370. set: function (value) {
  63371. if (this._blurRatio === value) {
  63372. return;
  63373. }
  63374. this._blurRatio = value;
  63375. this._preparePostProcesses();
  63376. },
  63377. enumerable: true,
  63378. configurable: true
  63379. });
  63380. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63381. set: function (value) {
  63382. this._adaptiveBlurKernel = value;
  63383. this._autoComputeBlurKernel();
  63384. },
  63385. enumerable: true,
  63386. configurable: true
  63387. });
  63388. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63389. set: function (value) {
  63390. this.blurKernelX = value;
  63391. this.blurKernelY = value;
  63392. },
  63393. enumerable: true,
  63394. configurable: true
  63395. });
  63396. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63397. get: function () {
  63398. return this._blurKernelX;
  63399. },
  63400. set: function (value) {
  63401. if (this._blurKernelX === value) {
  63402. return;
  63403. }
  63404. this._blurKernelX = value;
  63405. this._preparePostProcesses();
  63406. },
  63407. enumerable: true,
  63408. configurable: true
  63409. });
  63410. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63411. get: function () {
  63412. return this._blurKernelY;
  63413. },
  63414. set: function (value) {
  63415. if (this._blurKernelY === value) {
  63416. return;
  63417. }
  63418. this._blurKernelY = value;
  63419. this._preparePostProcesses();
  63420. },
  63421. enumerable: true,
  63422. configurable: true
  63423. });
  63424. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63425. var engine = this.getScene().getEngine();
  63426. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63427. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63428. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63429. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63430. };
  63431. MirrorTexture.prototype._onRatioRescale = function () {
  63432. if (this._sizeRatio) {
  63433. this.resize(this._initialSizeParameter);
  63434. if (!this._adaptiveBlurKernel) {
  63435. this._preparePostProcesses();
  63436. }
  63437. }
  63438. if (this._adaptiveBlurKernel) {
  63439. this._autoComputeBlurKernel();
  63440. }
  63441. };
  63442. MirrorTexture.prototype._updateGammaSpace = function () {
  63443. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63444. };
  63445. MirrorTexture.prototype._preparePostProcesses = function () {
  63446. this.clearPostProcesses(true);
  63447. if (this._blurKernelX && this._blurKernelY) {
  63448. var engine = this.getScene().getEngine();
  63449. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63450. 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);
  63451. this._blurX.autoClear = false;
  63452. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63453. this._blurX.inputTexture = this._texture;
  63454. }
  63455. else {
  63456. this._blurX.alwaysForcePOT = true;
  63457. }
  63458. 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);
  63459. this._blurY.autoClear = false;
  63460. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63461. this.addPostProcess(this._blurX);
  63462. this.addPostProcess(this._blurY);
  63463. }
  63464. else {
  63465. if (this._blurY) {
  63466. this.removePostProcess(this._blurY);
  63467. this._blurY.dispose();
  63468. this._blurY = null;
  63469. }
  63470. if (this._blurX) {
  63471. this.removePostProcess(this._blurX);
  63472. this._blurX.dispose();
  63473. this._blurX = null;
  63474. }
  63475. }
  63476. };
  63477. MirrorTexture.prototype.clone = function () {
  63478. var scene = this.getScene();
  63479. if (!scene) {
  63480. return this;
  63481. }
  63482. var textureSize = this.getSize();
  63483. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63484. // Base texture
  63485. newTexture.hasAlpha = this.hasAlpha;
  63486. newTexture.level = this.level;
  63487. // Mirror Texture
  63488. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63489. if (this.renderList) {
  63490. newTexture.renderList = this.renderList.slice(0);
  63491. }
  63492. return newTexture;
  63493. };
  63494. MirrorTexture.prototype.serialize = function () {
  63495. if (!this.name) {
  63496. return null;
  63497. }
  63498. var serializationObject = _super.prototype.serialize.call(this);
  63499. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63500. return serializationObject;
  63501. };
  63502. MirrorTexture.prototype.dispose = function () {
  63503. _super.prototype.dispose.call(this);
  63504. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63505. };
  63506. return MirrorTexture;
  63507. }(BABYLON.RenderTargetTexture));
  63508. BABYLON.MirrorTexture = MirrorTexture;
  63509. })(BABYLON || (BABYLON = {}));
  63510. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63511. var BABYLON;
  63512. (function (BABYLON) {
  63513. /**
  63514. * Creates a refraction texture used by refraction channel of the standard material.
  63515. * @param name the texture name
  63516. * @param size size of the underlying texture
  63517. * @param scene root scene
  63518. */
  63519. var RefractionTexture = /** @class */ (function (_super) {
  63520. __extends(RefractionTexture, _super);
  63521. function RefractionTexture(name, size, scene, generateMipMaps) {
  63522. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63523. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63524. _this.depth = 2.0;
  63525. _this.onBeforeRenderObservable.add(function () {
  63526. scene.clipPlane = _this.refractionPlane;
  63527. });
  63528. _this.onAfterRenderObservable.add(function () {
  63529. delete scene.clipPlane;
  63530. });
  63531. return _this;
  63532. }
  63533. RefractionTexture.prototype.clone = function () {
  63534. var scene = this.getScene();
  63535. if (!scene) {
  63536. return this;
  63537. }
  63538. var textureSize = this.getSize();
  63539. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63540. // Base texture
  63541. newTexture.hasAlpha = this.hasAlpha;
  63542. newTexture.level = this.level;
  63543. // Refraction Texture
  63544. newTexture.refractionPlane = this.refractionPlane.clone();
  63545. if (this.renderList) {
  63546. newTexture.renderList = this.renderList.slice(0);
  63547. }
  63548. newTexture.depth = this.depth;
  63549. return newTexture;
  63550. };
  63551. RefractionTexture.prototype.serialize = function () {
  63552. if (!this.name) {
  63553. return null;
  63554. }
  63555. var serializationObject = _super.prototype.serialize.call(this);
  63556. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63557. serializationObject.depth = this.depth;
  63558. return serializationObject;
  63559. };
  63560. return RefractionTexture;
  63561. }(BABYLON.RenderTargetTexture));
  63562. BABYLON.RefractionTexture = RefractionTexture;
  63563. })(BABYLON || (BABYLON = {}));
  63564. //# sourceMappingURL=babylon.refractionTexture.js.map
  63565. var BABYLON;
  63566. (function (BABYLON) {
  63567. /**
  63568. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63569. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63570. */
  63571. var DynamicTexture = /** @class */ (function (_super) {
  63572. __extends(DynamicTexture, _super);
  63573. /**
  63574. * Creates a {BABYLON.DynamicTexture}
  63575. * @param name defines the name of the texture
  63576. * @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
  63577. * @param scene defines the scene where you want the texture
  63578. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63579. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63580. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63581. */
  63582. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63583. if (scene === void 0) { scene = null; }
  63584. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63585. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63586. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63587. _this.name = name;
  63588. _this._engine = _this.getScene().getEngine();
  63589. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63590. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63591. _this._generateMipMaps = generateMipMaps;
  63592. if (options.getContext) {
  63593. _this._canvas = options;
  63594. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63595. }
  63596. else {
  63597. _this._canvas = document.createElement("canvas");
  63598. if (options.width || options.width === 0) {
  63599. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63600. }
  63601. else {
  63602. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63603. }
  63604. }
  63605. var textureSize = _this.getSize();
  63606. _this._canvas.width = textureSize.width;
  63607. _this._canvas.height = textureSize.height;
  63608. _this._context = _this._canvas.getContext("2d");
  63609. return _this;
  63610. }
  63611. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63612. /**
  63613. * Gets the current state of canRescale
  63614. */
  63615. get: function () {
  63616. return true;
  63617. },
  63618. enumerable: true,
  63619. configurable: true
  63620. });
  63621. DynamicTexture.prototype._recreate = function (textureSize) {
  63622. this._canvas.width = textureSize.width;
  63623. this._canvas.height = textureSize.height;
  63624. this.releaseInternalTexture();
  63625. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63626. };
  63627. /**
  63628. * Scales the texture
  63629. * @param ratio the scale factor to apply to both width and height
  63630. */
  63631. DynamicTexture.prototype.scale = function (ratio) {
  63632. var textureSize = this.getSize();
  63633. textureSize.width *= ratio;
  63634. textureSize.height *= ratio;
  63635. this._recreate(textureSize);
  63636. };
  63637. /**
  63638. * Resizes the texture
  63639. * @param width the new width
  63640. * @param height the new height
  63641. */
  63642. DynamicTexture.prototype.scaleTo = function (width, height) {
  63643. var textureSize = this.getSize();
  63644. textureSize.width = width;
  63645. textureSize.height = height;
  63646. this._recreate(textureSize);
  63647. };
  63648. /**
  63649. * Gets the context of the canvas used by the texture
  63650. * @returns the canvas context of the dynamic texture
  63651. */
  63652. DynamicTexture.prototype.getContext = function () {
  63653. return this._context;
  63654. };
  63655. /**
  63656. * Clears the texture
  63657. */
  63658. DynamicTexture.prototype.clear = function () {
  63659. var size = this.getSize();
  63660. this._context.fillRect(0, 0, size.width, size.height);
  63661. };
  63662. /**
  63663. * Updates the texture
  63664. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63665. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  63666. */
  63667. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  63668. if (premulAlpha === void 0) { premulAlpha = false; }
  63669. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  63670. };
  63671. /**
  63672. * Draws text onto the texture
  63673. * @param text defines the text to be drawn
  63674. * @param x defines the placement of the text from the left
  63675. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63676. * @param font defines the font to be used with font-style, font-size, font-name
  63677. * @param color defines the color used for the text
  63678. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63679. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63680. * @param update defines whether texture is immediately update (default is true)
  63681. */
  63682. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63683. if (update === void 0) { update = true; }
  63684. var size = this.getSize();
  63685. if (clearColor) {
  63686. this._context.fillStyle = clearColor;
  63687. this._context.fillRect(0, 0, size.width, size.height);
  63688. }
  63689. this._context.font = font;
  63690. if (x === null || x === undefined) {
  63691. var textSize = this._context.measureText(text);
  63692. x = (size.width - textSize.width) / 2;
  63693. }
  63694. if (y === null || y === undefined) {
  63695. var fontSize = parseInt((font.replace(/\D/g, '')));
  63696. y = (size.height / 2) + (fontSize / 3.65);
  63697. }
  63698. this._context.fillStyle = color;
  63699. this._context.fillText(text, x, y);
  63700. if (update) {
  63701. this.update(invertY);
  63702. }
  63703. };
  63704. /**
  63705. * Clones the texture
  63706. * @returns the clone of the texture.
  63707. */
  63708. DynamicTexture.prototype.clone = function () {
  63709. var scene = this.getScene();
  63710. if (!scene) {
  63711. return this;
  63712. }
  63713. var textureSize = this.getSize();
  63714. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63715. // Base texture
  63716. newTexture.hasAlpha = this.hasAlpha;
  63717. newTexture.level = this.level;
  63718. // Dynamic Texture
  63719. newTexture.wrapU = this.wrapU;
  63720. newTexture.wrapV = this.wrapV;
  63721. return newTexture;
  63722. };
  63723. /** @hidden */
  63724. DynamicTexture.prototype._rebuild = function () {
  63725. this.update();
  63726. };
  63727. return DynamicTexture;
  63728. }(BABYLON.Texture));
  63729. BABYLON.DynamicTexture = DynamicTexture;
  63730. })(BABYLON || (BABYLON = {}));
  63731. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63732. var BABYLON;
  63733. (function (BABYLON) {
  63734. var VideoTexture = /** @class */ (function (_super) {
  63735. __extends(VideoTexture, _super);
  63736. /**
  63737. * Creates a video texture.
  63738. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63739. * @param {string | null} name optional name, will detect from video source, if not defined
  63740. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63741. * @param {BABYLON.Scene} scene is obviously the current scene.
  63742. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63743. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63744. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63745. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63746. */
  63747. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63748. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63749. if (invertY === void 0) { invertY = false; }
  63750. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63751. if (settings === void 0) { settings = {
  63752. autoPlay: true,
  63753. loop: true,
  63754. autoUpdateTexture: true,
  63755. }; }
  63756. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63757. _this._stillImageCaptured = false;
  63758. _this._createInternalTexture = function () {
  63759. if (_this._texture != null) {
  63760. return;
  63761. }
  63762. if (!_this._engine.needPOTTextures ||
  63763. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63764. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63765. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63766. }
  63767. else {
  63768. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63769. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63770. _this._generateMipMaps = false;
  63771. }
  63772. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63773. if (!_this.video.autoplay) {
  63774. var oldHandler_1 = _this.video.onplaying;
  63775. _this.video.onplaying = function () {
  63776. _this.video.onplaying = oldHandler_1;
  63777. _this._texture.isReady = true;
  63778. _this._updateInternalTexture();
  63779. _this.video.pause();
  63780. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63781. _this.onLoadObservable.notifyObservers(_this);
  63782. }
  63783. };
  63784. _this.video.play();
  63785. }
  63786. else {
  63787. _this._texture.isReady = true;
  63788. _this._updateInternalTexture();
  63789. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63790. _this.onLoadObservable.notifyObservers(_this);
  63791. }
  63792. }
  63793. };
  63794. _this.reset = function () {
  63795. if (_this._texture == null) {
  63796. return;
  63797. }
  63798. _this._texture.dispose();
  63799. _this._texture = null;
  63800. };
  63801. _this._updateInternalTexture = function (e) {
  63802. if (_this._texture == null || !_this._texture.isReady) {
  63803. return;
  63804. }
  63805. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63806. return;
  63807. }
  63808. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63809. };
  63810. _this._engine = _this.getScene().getEngine();
  63811. _this._generateMipMaps = generateMipMaps;
  63812. _this._samplingMode = samplingMode;
  63813. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63814. _this.name = name || _this._getName(src);
  63815. _this.video = _this._getVideo(src);
  63816. if (settings.autoPlay !== undefined) {
  63817. _this.video.autoplay = settings.autoPlay;
  63818. }
  63819. if (settings.loop !== undefined) {
  63820. _this.video.loop = settings.loop;
  63821. }
  63822. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63823. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63824. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63825. _this.video.addEventListener("emptied", _this.reset);
  63826. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63827. _this._createInternalTexture();
  63828. }
  63829. return _this;
  63830. }
  63831. VideoTexture.prototype._getName = function (src) {
  63832. if (src instanceof HTMLVideoElement) {
  63833. return src.currentSrc;
  63834. }
  63835. if (typeof src === "object") {
  63836. return src.toString();
  63837. }
  63838. return src;
  63839. };
  63840. ;
  63841. VideoTexture.prototype._getVideo = function (src) {
  63842. if (src instanceof HTMLVideoElement) {
  63843. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63844. return src;
  63845. }
  63846. var video = document.createElement("video");
  63847. if (typeof src === "string") {
  63848. BABYLON.Tools.SetCorsBehavior(src, video);
  63849. video.src = src;
  63850. }
  63851. else {
  63852. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63853. src.forEach(function (url) {
  63854. var source = document.createElement("source");
  63855. source.src = url;
  63856. video.appendChild(source);
  63857. });
  63858. }
  63859. return video;
  63860. };
  63861. ;
  63862. /**
  63863. * Internal method to initiate `update`.
  63864. */
  63865. VideoTexture.prototype._rebuild = function () {
  63866. this.update();
  63867. };
  63868. /**
  63869. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63870. */
  63871. VideoTexture.prototype.update = function () {
  63872. if (!this.autoUpdateTexture) {
  63873. // Expecting user to call `updateTexture` manually
  63874. return;
  63875. }
  63876. this.updateTexture(true);
  63877. };
  63878. /**
  63879. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63880. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63881. */
  63882. VideoTexture.prototype.updateTexture = function (isVisible) {
  63883. if (!isVisible) {
  63884. return;
  63885. }
  63886. if (this.video.paused && this._stillImageCaptured) {
  63887. return;
  63888. }
  63889. this._stillImageCaptured = true;
  63890. this._updateInternalTexture();
  63891. };
  63892. /**
  63893. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63894. * @param url New url.
  63895. */
  63896. VideoTexture.prototype.updateURL = function (url) {
  63897. this.video.src = url;
  63898. };
  63899. VideoTexture.prototype.dispose = function () {
  63900. _super.prototype.dispose.call(this);
  63901. this.video.removeEventListener("canplay", this._createInternalTexture);
  63902. this.video.removeEventListener("paused", this._updateInternalTexture);
  63903. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63904. this.video.removeEventListener("emptied", this.reset);
  63905. this.video.pause();
  63906. };
  63907. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63908. var video = document.createElement("video");
  63909. var constraintsDeviceId;
  63910. if (constraints && constraints.deviceId) {
  63911. constraintsDeviceId = {
  63912. exact: constraints.deviceId,
  63913. };
  63914. }
  63915. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63916. if (navigator.mediaDevices) {
  63917. navigator.mediaDevices.getUserMedia({ video: constraints })
  63918. .then(function (stream) {
  63919. if (video.mozSrcObject !== undefined) {
  63920. // hack for Firefox < 19
  63921. video.mozSrcObject = stream;
  63922. }
  63923. else {
  63924. video.srcObject = stream;
  63925. }
  63926. var onPlaying = function () {
  63927. if (onReady) {
  63928. onReady(new VideoTexture("video", video, scene, true, true));
  63929. }
  63930. video.removeEventListener("playing", onPlaying);
  63931. };
  63932. video.addEventListener("playing", onPlaying);
  63933. video.play();
  63934. })
  63935. .catch(function (err) {
  63936. BABYLON.Tools.Error(err.name);
  63937. });
  63938. }
  63939. else {
  63940. navigator.getUserMedia =
  63941. navigator.getUserMedia ||
  63942. navigator.webkitGetUserMedia ||
  63943. navigator.mozGetUserMedia ||
  63944. navigator.msGetUserMedia;
  63945. if (navigator.getUserMedia) {
  63946. navigator.getUserMedia({
  63947. video: {
  63948. deviceId: constraintsDeviceId,
  63949. width: {
  63950. min: (constraints && constraints.minWidth) || 256,
  63951. max: (constraints && constraints.maxWidth) || 640,
  63952. },
  63953. height: {
  63954. min: (constraints && constraints.minHeight) || 256,
  63955. max: (constraints && constraints.maxHeight) || 480,
  63956. },
  63957. },
  63958. }, function (stream) {
  63959. if (video.mozSrcObject !== undefined) {
  63960. // hack for Firefox < 19
  63961. video.mozSrcObject = stream;
  63962. }
  63963. else {
  63964. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  63965. }
  63966. video.play();
  63967. if (onReady) {
  63968. onReady(new VideoTexture("video", video, scene, true, true));
  63969. }
  63970. }, function (e) {
  63971. BABYLON.Tools.Error(e.name);
  63972. });
  63973. }
  63974. }
  63975. };
  63976. return VideoTexture;
  63977. }(BABYLON.Texture));
  63978. BABYLON.VideoTexture = VideoTexture;
  63979. })(BABYLON || (BABYLON = {}));
  63980. //# sourceMappingURL=babylon.videoTexture.js.map
  63981. var BABYLON;
  63982. (function (BABYLON) {
  63983. var RawTexture = /** @class */ (function (_super) {
  63984. __extends(RawTexture, _super);
  63985. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  63986. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63987. if (invertY === void 0) { invertY = false; }
  63988. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63989. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63990. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63991. _this.format = format;
  63992. _this._engine = scene.getEngine();
  63993. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  63994. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63995. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63996. return _this;
  63997. }
  63998. RawTexture.prototype.update = function (data) {
  63999. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64000. };
  64001. // Statics
  64002. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64003. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64004. if (invertY === void 0) { invertY = false; }
  64005. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64006. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64007. };
  64008. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64009. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64010. if (invertY === void 0) { invertY = false; }
  64011. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64012. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64013. };
  64014. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64015. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64016. if (invertY === void 0) { invertY = false; }
  64017. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64018. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64019. };
  64020. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64021. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64022. if (invertY === void 0) { invertY = false; }
  64023. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64024. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64025. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64026. };
  64027. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64028. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64029. if (invertY === void 0) { invertY = false; }
  64030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64031. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64032. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64033. };
  64034. return RawTexture;
  64035. }(BABYLON.Texture));
  64036. BABYLON.RawTexture = RawTexture;
  64037. })(BABYLON || (BABYLON = {}));
  64038. //# sourceMappingURL=babylon.rawTexture.js.map
  64039. var BABYLON;
  64040. (function (BABYLON) {
  64041. /**
  64042. * Class used to store 3D textures containing user data
  64043. */
  64044. var RawTexture3D = /** @class */ (function (_super) {
  64045. __extends(RawTexture3D, _super);
  64046. /**
  64047. * Create a new RawTexture3D
  64048. * @param data defines the data of the texture
  64049. * @param width defines the width of the texture
  64050. * @param height defines the height of the texture
  64051. * @param depth defines the depth of the texture
  64052. * @param format defines the texture format to use
  64053. * @param scene defines the hosting scene
  64054. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64055. * @param invertY defines if texture must be stored with Y axis inverted
  64056. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64057. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64058. */
  64059. function RawTexture3D(data, width, height, depth,
  64060. /** Gets or sets the texture format to use */
  64061. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64062. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64063. if (invertY === void 0) { invertY = false; }
  64064. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64065. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64066. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64067. _this.format = format;
  64068. _this._engine = scene.getEngine();
  64069. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64070. _this.is3D = true;
  64071. return _this;
  64072. }
  64073. /**
  64074. * Update the texture with new data
  64075. * @param data defines the data to store in the texture
  64076. */
  64077. RawTexture3D.prototype.update = function (data) {
  64078. if (!this._texture) {
  64079. return;
  64080. }
  64081. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64082. };
  64083. return RawTexture3D;
  64084. }(BABYLON.Texture));
  64085. BABYLON.RawTexture3D = RawTexture3D;
  64086. })(BABYLON || (BABYLON = {}));
  64087. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64088. var BABYLON;
  64089. (function (BABYLON) {
  64090. /**
  64091. * PostProcessManager is used to manage one or more post processes or post process pipelines
  64092. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64093. */
  64094. var PostProcessManager = /** @class */ (function () {
  64095. /**
  64096. * Creates a new instance PostProcess
  64097. * @param scene The scene that the post process is associated with.
  64098. */
  64099. function PostProcessManager(scene) {
  64100. this._vertexBuffers = {};
  64101. this._scene = scene;
  64102. }
  64103. PostProcessManager.prototype._prepareBuffers = function () {
  64104. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  64105. return;
  64106. }
  64107. // VBO
  64108. var vertices = [];
  64109. vertices.push(1, 1);
  64110. vertices.push(-1, 1);
  64111. vertices.push(-1, -1);
  64112. vertices.push(1, -1);
  64113. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64114. this._buildIndexBuffer();
  64115. };
  64116. PostProcessManager.prototype._buildIndexBuffer = function () {
  64117. // Indices
  64118. var indices = [];
  64119. indices.push(0);
  64120. indices.push(1);
  64121. indices.push(2);
  64122. indices.push(0);
  64123. indices.push(2);
  64124. indices.push(3);
  64125. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  64126. };
  64127. /**
  64128. * Rebuilds the vertex buffers of the manager.
  64129. */
  64130. PostProcessManager.prototype._rebuild = function () {
  64131. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64132. if (!vb) {
  64133. return;
  64134. }
  64135. vb._rebuild();
  64136. this._buildIndexBuffer();
  64137. };
  64138. // Methods
  64139. /**
  64140. * Prepares a frame to be run through a post process.
  64141. * @param sourceTexture The input texture to the post procesess. (default: null)
  64142. * @param postProcesses An array of post processes to be run. (default: null)
  64143. * @returns True if the post processes were able to be run.
  64144. */
  64145. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  64146. if (sourceTexture === void 0) { sourceTexture = null; }
  64147. if (postProcesses === void 0) { postProcesses = null; }
  64148. var camera = this._scene.activeCamera;
  64149. if (!camera) {
  64150. return false;
  64151. }
  64152. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64153. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64154. return false;
  64155. }
  64156. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  64157. return true;
  64158. };
  64159. /**
  64160. * Manually render a set of post processes to a texture.
  64161. * @param postProcesses An array of post processes to be run.
  64162. * @param targetTexture The target texture to render to.
  64163. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  64164. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  64165. * @param lodLevel defines which lod of the texture to render to
  64166. */
  64167. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  64168. if (targetTexture === void 0) { targetTexture = null; }
  64169. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64170. if (faceIndex === void 0) { faceIndex = 0; }
  64171. if (lodLevel === void 0) { lodLevel = 0; }
  64172. var engine = this._scene.getEngine();
  64173. for (var index = 0; index < postProcesses.length; index++) {
  64174. if (index < postProcesses.length - 1) {
  64175. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  64176. }
  64177. else {
  64178. if (targetTexture) {
  64179. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  64180. }
  64181. else {
  64182. engine.restoreDefaultFramebuffer();
  64183. }
  64184. }
  64185. var pp = postProcesses[index];
  64186. var effect = pp.apply();
  64187. if (effect) {
  64188. pp.onBeforeRenderObservable.notifyObservers(effect);
  64189. // VBOs
  64190. this._prepareBuffers();
  64191. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64192. // Draw order
  64193. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64194. pp.onAfterRenderObservable.notifyObservers(effect);
  64195. }
  64196. }
  64197. // Restore depth buffer
  64198. engine.setDepthBuffer(true);
  64199. engine.setDepthWrite(true);
  64200. };
  64201. /**
  64202. * Finalize the result of the output of the postprocesses.
  64203. * @param doNotPresent If true the result will not be displayed to the screen.
  64204. * @param targetTexture The target texture to render to.
  64205. * @param faceIndex The index of the face to bind the target texture to.
  64206. * @param postProcesses The array of post processes to render.
  64207. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  64208. */
  64209. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  64210. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64211. var camera = this._scene.activeCamera;
  64212. if (!camera) {
  64213. return;
  64214. }
  64215. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64216. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64217. return;
  64218. }
  64219. var engine = this._scene.getEngine();
  64220. for (var index = 0, len = postProcesses.length; index < len; index++) {
  64221. var pp = postProcesses[index];
  64222. if (index < len - 1) {
  64223. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  64224. }
  64225. else {
  64226. if (targetTexture) {
  64227. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  64228. pp._outputTexture = targetTexture;
  64229. }
  64230. else {
  64231. engine.restoreDefaultFramebuffer();
  64232. pp._outputTexture = null;
  64233. }
  64234. }
  64235. if (doNotPresent) {
  64236. break;
  64237. }
  64238. var effect = pp.apply();
  64239. if (effect) {
  64240. pp.onBeforeRenderObservable.notifyObservers(effect);
  64241. // VBOs
  64242. this._prepareBuffers();
  64243. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64244. // Draw order
  64245. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64246. pp.onAfterRenderObservable.notifyObservers(effect);
  64247. }
  64248. }
  64249. // Restore states
  64250. engine.setDepthBuffer(true);
  64251. engine.setDepthWrite(true);
  64252. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64253. };
  64254. /**
  64255. * Disposes of the post process manager.
  64256. */
  64257. PostProcessManager.prototype.dispose = function () {
  64258. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64259. if (buffer) {
  64260. buffer.dispose();
  64261. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64262. }
  64263. if (this._indexBuffer) {
  64264. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64265. this._indexBuffer = null;
  64266. }
  64267. };
  64268. return PostProcessManager;
  64269. }());
  64270. BABYLON.PostProcessManager = PostProcessManager;
  64271. })(BABYLON || (BABYLON = {}));
  64272. //# sourceMappingURL=babylon.postProcessManager.js.map
  64273. var BABYLON;
  64274. (function (BABYLON) {
  64275. /**
  64276. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64277. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64278. */
  64279. var PostProcess = /** @class */ (function () {
  64280. /**
  64281. * Creates a new instance PostProcess
  64282. * @param name The name of the PostProcess.
  64283. * @param fragmentUrl The url of the fragment shader to be used.
  64284. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64285. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64286. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64287. * @param camera The camera to apply the render pass to.
  64288. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64289. * @param engine The engine which the post process will be applied. (default: current engine)
  64290. * @param reusable If the post process can be reused on the same frame. (default: false)
  64291. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64292. * @param textureType Type of textures used when performing the post process. (default: 0)
  64293. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64294. * @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
  64295. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64296. */
  64297. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64298. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64299. if (defines === void 0) { defines = null; }
  64300. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64301. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64302. if (blockCompilation === void 0) { blockCompilation = false; }
  64303. this.name = name;
  64304. /**
  64305. * Width of the texture to apply the post process on
  64306. */
  64307. this.width = -1;
  64308. /**
  64309. * Height of the texture to apply the post process on
  64310. */
  64311. this.height = -1;
  64312. /**
  64313. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64314. */
  64315. this._outputTexture = null;
  64316. /**
  64317. * If the buffer needs to be cleared before applying the post process. (default: true)
  64318. * Should be set to false if shader will overwrite all previous pixels.
  64319. */
  64320. this.autoClear = true;
  64321. /**
  64322. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64323. */
  64324. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64325. /**
  64326. * Animations to be used for the post processing
  64327. */
  64328. this.animations = new Array();
  64329. /**
  64330. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64331. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64332. */
  64333. this.enablePixelPerfectMode = false;
  64334. /**
  64335. * Force the postprocess to be applied without taking in account viewport
  64336. */
  64337. this.forceFullscreenViewport = true;
  64338. /**
  64339. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64340. *
  64341. * | Value | Type | Description |
  64342. * | ----- | ----------------------------------- | ----------- |
  64343. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  64344. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  64345. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  64346. *
  64347. */
  64348. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64349. /**
  64350. * Force textures to be a power of two (default: false)
  64351. */
  64352. this.alwaysForcePOT = false;
  64353. /**
  64354. * Number of sample textures (default: 1)
  64355. */
  64356. this.samples = 1;
  64357. /**
  64358. * Modify the scale of the post process to be the same as the viewport (default: false)
  64359. */
  64360. this.adaptScaleToCurrentViewport = false;
  64361. this._reusable = false;
  64362. /**
  64363. * Smart array of input and output textures for the post process.
  64364. */
  64365. this._textures = new BABYLON.SmartArray(2);
  64366. /**
  64367. * The index in _textures that corresponds to the output texture.
  64368. */
  64369. this._currentRenderTextureInd = 0;
  64370. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64371. this._texelSize = BABYLON.Vector2.Zero();
  64372. // Events
  64373. /**
  64374. * An event triggered when the postprocess is activated.
  64375. */
  64376. this.onActivateObservable = new BABYLON.Observable();
  64377. /**
  64378. * An event triggered when the postprocess changes its size.
  64379. */
  64380. this.onSizeChangedObservable = new BABYLON.Observable();
  64381. /**
  64382. * An event triggered when the postprocess applies its effect.
  64383. */
  64384. this.onApplyObservable = new BABYLON.Observable();
  64385. /**
  64386. * An event triggered before rendering the postprocess
  64387. */
  64388. this.onBeforeRenderObservable = new BABYLON.Observable();
  64389. /**
  64390. * An event triggered after rendering the postprocess
  64391. */
  64392. this.onAfterRenderObservable = new BABYLON.Observable();
  64393. if (camera != null) {
  64394. this._camera = camera;
  64395. this._scene = camera.getScene();
  64396. camera.attachPostProcess(this);
  64397. this._engine = this._scene.getEngine();
  64398. this._scene.postProcesses.push(this);
  64399. }
  64400. else if (engine) {
  64401. this._engine = engine;
  64402. this._engine.postProcesses.push(this);
  64403. }
  64404. this._options = options;
  64405. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64406. this._reusable = reusable || false;
  64407. this._textureType = textureType;
  64408. this._samplers = samplers || [];
  64409. this._samplers.push("textureSampler");
  64410. this._fragmentUrl = fragmentUrl;
  64411. this._vertexUrl = vertexUrl;
  64412. this._parameters = parameters || [];
  64413. this._parameters.push("scale");
  64414. this._indexParameters = indexParameters;
  64415. if (!blockCompilation) {
  64416. this.updateEffect(defines);
  64417. }
  64418. }
  64419. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64420. /**
  64421. * A function that is added to the onActivateObservable
  64422. */
  64423. set: function (callback) {
  64424. if (this._onActivateObserver) {
  64425. this.onActivateObservable.remove(this._onActivateObserver);
  64426. }
  64427. if (callback) {
  64428. this._onActivateObserver = this.onActivateObservable.add(callback);
  64429. }
  64430. },
  64431. enumerable: true,
  64432. configurable: true
  64433. });
  64434. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64435. /**
  64436. * A function that is added to the onSizeChangedObservable
  64437. */
  64438. set: function (callback) {
  64439. if (this._onSizeChangedObserver) {
  64440. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64441. }
  64442. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64443. },
  64444. enumerable: true,
  64445. configurable: true
  64446. });
  64447. Object.defineProperty(PostProcess.prototype, "onApply", {
  64448. /**
  64449. * A function that is added to the onApplyObservable
  64450. */
  64451. set: function (callback) {
  64452. if (this._onApplyObserver) {
  64453. this.onApplyObservable.remove(this._onApplyObserver);
  64454. }
  64455. this._onApplyObserver = this.onApplyObservable.add(callback);
  64456. },
  64457. enumerable: true,
  64458. configurable: true
  64459. });
  64460. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64461. /**
  64462. * A function that is added to the onBeforeRenderObservable
  64463. */
  64464. set: function (callback) {
  64465. if (this._onBeforeRenderObserver) {
  64466. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64467. }
  64468. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64469. },
  64470. enumerable: true,
  64471. configurable: true
  64472. });
  64473. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64474. /**
  64475. * A function that is added to the onAfterRenderObservable
  64476. */
  64477. set: function (callback) {
  64478. if (this._onAfterRenderObserver) {
  64479. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64480. }
  64481. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64482. },
  64483. enumerable: true,
  64484. configurable: true
  64485. });
  64486. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64487. /**
  64488. * 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
  64489. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64490. */
  64491. get: function () {
  64492. return this._textures.data[this._currentRenderTextureInd];
  64493. },
  64494. set: function (value) {
  64495. this._forcedOutputTexture = value;
  64496. },
  64497. enumerable: true,
  64498. configurable: true
  64499. });
  64500. /**
  64501. * Gets the camera which post process is applied to.
  64502. * @returns The camera the post process is applied to.
  64503. */
  64504. PostProcess.prototype.getCamera = function () {
  64505. return this._camera;
  64506. };
  64507. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64508. /**
  64509. * Gets the texel size of the postprocess.
  64510. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64511. */
  64512. get: function () {
  64513. if (this._shareOutputWithPostProcess) {
  64514. return this._shareOutputWithPostProcess.texelSize;
  64515. }
  64516. if (this._forcedOutputTexture) {
  64517. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64518. }
  64519. return this._texelSize;
  64520. },
  64521. enumerable: true,
  64522. configurable: true
  64523. });
  64524. /**
  64525. * Gets the engine which this post process belongs to.
  64526. * @returns The engine the post process was enabled with.
  64527. */
  64528. PostProcess.prototype.getEngine = function () {
  64529. return this._engine;
  64530. };
  64531. /**
  64532. * The effect that is created when initializing the post process.
  64533. * @returns The created effect corrisponding the the postprocess.
  64534. */
  64535. PostProcess.prototype.getEffect = function () {
  64536. return this._effect;
  64537. };
  64538. /**
  64539. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64540. * @param postProcess The post process to share the output with.
  64541. * @returns This post process.
  64542. */
  64543. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64544. this._disposeTextures();
  64545. this._shareOutputWithPostProcess = postProcess;
  64546. return this;
  64547. };
  64548. /**
  64549. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64550. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64551. */
  64552. PostProcess.prototype.useOwnOutput = function () {
  64553. if (this._textures.length == 0) {
  64554. this._textures = new BABYLON.SmartArray(2);
  64555. }
  64556. this._shareOutputWithPostProcess = null;
  64557. };
  64558. /**
  64559. * Updates the effect with the current post process compile time values and recompiles the shader.
  64560. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64561. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64562. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64563. * @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
  64564. * @param onCompiled Called when the shader has been compiled.
  64565. * @param onError Called if there is an error when compiling a shader.
  64566. */
  64567. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64568. if (defines === void 0) { defines = null; }
  64569. if (uniforms === void 0) { uniforms = null; }
  64570. if (samplers === void 0) { samplers = null; }
  64571. 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);
  64572. };
  64573. /**
  64574. * The post process is reusable if it can be used multiple times within one frame.
  64575. * @returns If the post process is reusable
  64576. */
  64577. PostProcess.prototype.isReusable = function () {
  64578. return this._reusable;
  64579. };
  64580. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64581. PostProcess.prototype.markTextureDirty = function () {
  64582. this.width = -1;
  64583. };
  64584. /**
  64585. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64586. * 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.
  64587. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64588. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64589. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64590. * @returns The target texture that was bound to be written to.
  64591. */
  64592. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64593. var _this = this;
  64594. if (sourceTexture === void 0) { sourceTexture = null; }
  64595. camera = camera || this._camera;
  64596. var scene = camera.getScene();
  64597. var engine = scene.getEngine();
  64598. var maxSize = engine.getCaps().maxTextureSize;
  64599. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64600. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64601. // 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
  64602. var webVRCamera = camera.parent;
  64603. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64604. requiredWidth /= 2;
  64605. }
  64606. var desiredWidth = (this._options.width || requiredWidth);
  64607. var desiredHeight = this._options.height || requiredHeight;
  64608. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64609. if (this.adaptScaleToCurrentViewport) {
  64610. var currentViewport = engine.currentViewport;
  64611. if (currentViewport) {
  64612. desiredWidth *= currentViewport.width;
  64613. desiredHeight *= currentViewport.height;
  64614. }
  64615. }
  64616. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64617. if (!this._options.width) {
  64618. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64619. }
  64620. if (!this._options.height) {
  64621. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64622. }
  64623. }
  64624. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64625. if (this._textures.length > 0) {
  64626. for (var i = 0; i < this._textures.length; i++) {
  64627. this._engine._releaseTexture(this._textures.data[i]);
  64628. }
  64629. this._textures.reset();
  64630. }
  64631. this.width = desiredWidth;
  64632. this.height = desiredHeight;
  64633. var textureSize = { width: this.width, height: this.height };
  64634. var textureOptions = {
  64635. generateMipMaps: false,
  64636. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64637. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64638. samplingMode: this.renderTargetSamplingMode,
  64639. type: this._textureType
  64640. };
  64641. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64642. if (this._reusable) {
  64643. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64644. }
  64645. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64646. this.onSizeChangedObservable.notifyObservers(this);
  64647. }
  64648. this._textures.forEach(function (texture) {
  64649. if (texture.samples !== _this.samples) {
  64650. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64651. }
  64652. });
  64653. }
  64654. var target;
  64655. if (this._shareOutputWithPostProcess) {
  64656. target = this._shareOutputWithPostProcess.inputTexture;
  64657. }
  64658. else if (this._forcedOutputTexture) {
  64659. target = this._forcedOutputTexture;
  64660. this.width = this._forcedOutputTexture.width;
  64661. this.height = this._forcedOutputTexture.height;
  64662. }
  64663. else {
  64664. target = this.inputTexture;
  64665. }
  64666. // Bind the input of this post process to be used as the output of the previous post process.
  64667. if (this.enablePixelPerfectMode) {
  64668. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64669. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  64670. }
  64671. else {
  64672. this._scaleRatio.copyFromFloats(1, 1);
  64673. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  64674. }
  64675. this.onActivateObservable.notifyObservers(camera);
  64676. // Clear
  64677. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  64678. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  64679. }
  64680. if (this._reusable) {
  64681. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  64682. }
  64683. return target;
  64684. };
  64685. Object.defineProperty(PostProcess.prototype, "isSupported", {
  64686. /**
  64687. * If the post process is supported.
  64688. */
  64689. get: function () {
  64690. return this._effect.isSupported;
  64691. },
  64692. enumerable: true,
  64693. configurable: true
  64694. });
  64695. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  64696. /**
  64697. * The aspect ratio of the output texture.
  64698. */
  64699. get: function () {
  64700. if (this._shareOutputWithPostProcess) {
  64701. return this._shareOutputWithPostProcess.aspectRatio;
  64702. }
  64703. if (this._forcedOutputTexture) {
  64704. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  64705. }
  64706. return this.width / this.height;
  64707. },
  64708. enumerable: true,
  64709. configurable: true
  64710. });
  64711. /**
  64712. * Get a value indicating if the post-process is ready to be used
  64713. * @returns true if the post-process is ready (shader is compiled)
  64714. */
  64715. PostProcess.prototype.isReady = function () {
  64716. return this._effect && this._effect.isReady();
  64717. };
  64718. /**
  64719. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64720. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64721. */
  64722. PostProcess.prototype.apply = function () {
  64723. // Check
  64724. if (!this._effect || !this._effect.isReady())
  64725. return null;
  64726. // States
  64727. this._engine.enableEffect(this._effect);
  64728. this._engine.setState(false);
  64729. this._engine.setDepthBuffer(false);
  64730. this._engine.setDepthWrite(false);
  64731. // Alpha
  64732. this._engine.setAlphaMode(this.alphaMode);
  64733. if (this.alphaConstants) {
  64734. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64735. }
  64736. // Bind the output texture of the preivous post process as the input to this post process.
  64737. var source;
  64738. if (this._shareOutputWithPostProcess) {
  64739. source = this._shareOutputWithPostProcess.inputTexture;
  64740. }
  64741. else if (this._forcedOutputTexture) {
  64742. source = this._forcedOutputTexture;
  64743. }
  64744. else {
  64745. source = this.inputTexture;
  64746. }
  64747. this._effect._bindTexture("textureSampler", source);
  64748. // Parameters
  64749. this._effect.setVector2("scale", this._scaleRatio);
  64750. this.onApplyObservable.notifyObservers(this._effect);
  64751. return this._effect;
  64752. };
  64753. PostProcess.prototype._disposeTextures = function () {
  64754. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64755. return;
  64756. }
  64757. if (this._textures.length > 0) {
  64758. for (var i = 0; i < this._textures.length; i++) {
  64759. this._engine._releaseTexture(this._textures.data[i]);
  64760. }
  64761. }
  64762. this._textures.dispose();
  64763. };
  64764. /**
  64765. * Disposes the post process.
  64766. * @param camera The camera to dispose the post process on.
  64767. */
  64768. PostProcess.prototype.dispose = function (camera) {
  64769. camera = camera || this._camera;
  64770. this._disposeTextures();
  64771. if (this._scene) {
  64772. var index_1 = this._scene.postProcesses.indexOf(this);
  64773. if (index_1 !== -1) {
  64774. this._scene.postProcesses.splice(index_1, 1);
  64775. }
  64776. }
  64777. else {
  64778. var index_2 = this._engine.postProcesses.indexOf(this);
  64779. if (index_2 !== -1) {
  64780. this._engine.postProcesses.splice(index_2, 1);
  64781. }
  64782. }
  64783. if (!camera) {
  64784. return;
  64785. }
  64786. camera.detachPostProcess(this);
  64787. var index = camera._postProcesses.indexOf(this);
  64788. if (index === 0 && camera._postProcesses.length > 0) {
  64789. var firstPostProcess = this._camera._getFirstPostProcess();
  64790. if (firstPostProcess) {
  64791. firstPostProcess.markTextureDirty();
  64792. }
  64793. }
  64794. this.onActivateObservable.clear();
  64795. this.onAfterRenderObservable.clear();
  64796. this.onApplyObservable.clear();
  64797. this.onBeforeRenderObservable.clear();
  64798. this.onSizeChangedObservable.clear();
  64799. };
  64800. return PostProcess;
  64801. }());
  64802. BABYLON.PostProcess = PostProcess;
  64803. })(BABYLON || (BABYLON = {}));
  64804. //# sourceMappingURL=babylon.postProcess.js.map
  64805. var BABYLON;
  64806. (function (BABYLON) {
  64807. var PassPostProcess = /** @class */ (function (_super) {
  64808. __extends(PassPostProcess, _super);
  64809. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64810. if (camera === void 0) { camera = null; }
  64811. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64812. if (blockCompilation === void 0) { blockCompilation = false; }
  64813. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64814. }
  64815. return PassPostProcess;
  64816. }(BABYLON.PostProcess));
  64817. BABYLON.PassPostProcess = PassPostProcess;
  64818. })(BABYLON || (BABYLON = {}));
  64819. //# sourceMappingURL=babylon.passPostProcess.js.map
  64820. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64821. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64822. s = arguments[i];
  64823. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64824. t[p] = s[p];
  64825. }
  64826. return t;
  64827. };
  64828. var BABYLON;
  64829. (function (BABYLON) {
  64830. /**
  64831. * Default implementation IShadowGenerator.
  64832. * This is the main object responsible of generating shadows in the framework.
  64833. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64834. */
  64835. var ShadowGenerator = /** @class */ (function () {
  64836. /**
  64837. * Creates a ShadowGenerator object.
  64838. * A ShadowGenerator is the required tool to use the shadows.
  64839. * Each light casting shadows needs to use its own ShadowGenerator.
  64840. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64841. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64842. * @param light The light object generating the shadows.
  64843. * @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.
  64844. */
  64845. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64846. this._bias = 0.00005;
  64847. this._normalBias = 0;
  64848. this._blurBoxOffset = 1;
  64849. this._blurScale = 2;
  64850. this._blurKernel = 1;
  64851. this._useKernelBlur = false;
  64852. this._filter = ShadowGenerator.FILTER_NONE;
  64853. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64854. this._contactHardeningLightSizeUVRatio = 0.1;
  64855. this._darkness = 0;
  64856. this._transparencyShadow = false;
  64857. /**
  64858. * Controls the extent to which the shadows fade out at the edge of the frustum
  64859. * Used only by directionals and spots
  64860. */
  64861. this.frustumEdgeFalloff = 0;
  64862. /**
  64863. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64864. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64865. * It might on the other hand introduce peter panning.
  64866. */
  64867. this.forceBackFacesOnly = false;
  64868. this._lightDirection = BABYLON.Vector3.Zero();
  64869. this._viewMatrix = BABYLON.Matrix.Zero();
  64870. this._projectionMatrix = BABYLON.Matrix.Zero();
  64871. this._transformMatrix = BABYLON.Matrix.Zero();
  64872. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64873. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64874. this._currentFaceIndex = 0;
  64875. this._currentFaceIndexCache = 0;
  64876. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64877. this._mapSize = mapSize;
  64878. this._light = light;
  64879. this._scene = light.getScene();
  64880. light._shadowGenerator = this;
  64881. // Texture type fallback from float to int if not supported.
  64882. var caps = this._scene.getEngine().getCaps();
  64883. if (!useFullFloatFirst) {
  64884. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64885. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64886. }
  64887. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64888. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64889. }
  64890. else {
  64891. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64892. }
  64893. }
  64894. else {
  64895. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64896. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64897. }
  64898. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64899. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64900. }
  64901. else {
  64902. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64903. }
  64904. }
  64905. this._initializeGenerator();
  64906. this._applyFilterValues();
  64907. }
  64908. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64909. /**
  64910. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64911. */
  64912. get: function () {
  64913. return this._bias;
  64914. },
  64915. /**
  64916. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64917. */
  64918. set: function (bias) {
  64919. this._bias = bias;
  64920. },
  64921. enumerable: true,
  64922. configurable: true
  64923. });
  64924. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  64925. /**
  64926. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64927. */
  64928. get: function () {
  64929. return this._normalBias;
  64930. },
  64931. /**
  64932. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64933. */
  64934. set: function (normalBias) {
  64935. this._normalBias = normalBias;
  64936. },
  64937. enumerable: true,
  64938. configurable: true
  64939. });
  64940. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  64941. /**
  64942. * Gets the blur box offset: offset applied during the blur pass.
  64943. * Only usefull if useKernelBlur = false
  64944. */
  64945. get: function () {
  64946. return this._blurBoxOffset;
  64947. },
  64948. /**
  64949. * Sets the blur box offset: offset applied during the blur pass.
  64950. * Only usefull if useKernelBlur = false
  64951. */
  64952. set: function (value) {
  64953. if (this._blurBoxOffset === value) {
  64954. return;
  64955. }
  64956. this._blurBoxOffset = value;
  64957. this._disposeBlurPostProcesses();
  64958. },
  64959. enumerable: true,
  64960. configurable: true
  64961. });
  64962. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  64963. /**
  64964. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  64965. * 2 means half of the size.
  64966. */
  64967. get: function () {
  64968. return this._blurScale;
  64969. },
  64970. /**
  64971. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  64972. * 2 means half of the size.
  64973. */
  64974. set: function (value) {
  64975. if (this._blurScale === value) {
  64976. return;
  64977. }
  64978. this._blurScale = value;
  64979. this._disposeBlurPostProcesses();
  64980. },
  64981. enumerable: true,
  64982. configurable: true
  64983. });
  64984. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  64985. /**
  64986. * Gets the blur kernel: kernel size of the blur pass.
  64987. * Only usefull if useKernelBlur = true
  64988. */
  64989. get: function () {
  64990. return this._blurKernel;
  64991. },
  64992. /**
  64993. * Sets the blur kernel: kernel size of the blur pass.
  64994. * Only usefull if useKernelBlur = true
  64995. */
  64996. set: function (value) {
  64997. if (this._blurKernel === value) {
  64998. return;
  64999. }
  65000. this._blurKernel = value;
  65001. this._disposeBlurPostProcesses();
  65002. },
  65003. enumerable: true,
  65004. configurable: true
  65005. });
  65006. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65007. /**
  65008. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65009. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65010. */
  65011. get: function () {
  65012. return this._useKernelBlur;
  65013. },
  65014. /**
  65015. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65016. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65017. */
  65018. set: function (value) {
  65019. if (this._useKernelBlur === value) {
  65020. return;
  65021. }
  65022. this._useKernelBlur = value;
  65023. this._disposeBlurPostProcesses();
  65024. },
  65025. enumerable: true,
  65026. configurable: true
  65027. });
  65028. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65029. /**
  65030. * Gets the depth scale used in ESM mode.
  65031. */
  65032. get: function () {
  65033. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65034. },
  65035. /**
  65036. * Sets the depth scale used in ESM mode.
  65037. * This can override the scale stored on the light.
  65038. */
  65039. set: function (value) {
  65040. this._depthScale = value;
  65041. },
  65042. enumerable: true,
  65043. configurable: true
  65044. });
  65045. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65046. /**
  65047. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65048. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65049. */
  65050. get: function () {
  65051. return this._filter;
  65052. },
  65053. /**
  65054. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65055. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65056. */
  65057. set: function (value) {
  65058. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65059. if (this._light.needCube()) {
  65060. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65061. this.useExponentialShadowMap = true;
  65062. return;
  65063. }
  65064. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65065. this.useCloseExponentialShadowMap = true;
  65066. return;
  65067. }
  65068. // PCF on cubemap would also be expensive
  65069. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65070. this.usePoissonSampling = true;
  65071. return;
  65072. }
  65073. }
  65074. // Weblg1 fallback for PCF.
  65075. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65076. if (this._scene.getEngine().webGLVersion === 1) {
  65077. this.usePoissonSampling = true;
  65078. return;
  65079. }
  65080. }
  65081. if (this._filter === value) {
  65082. return;
  65083. }
  65084. this._filter = value;
  65085. this._disposeBlurPostProcesses();
  65086. this._applyFilterValues();
  65087. this._light._markMeshesAsLightDirty();
  65088. },
  65089. enumerable: true,
  65090. configurable: true
  65091. });
  65092. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65093. /**
  65094. * Gets if the current filter is set to Poisson Sampling.
  65095. */
  65096. get: function () {
  65097. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65098. },
  65099. /**
  65100. * Sets the current filter to Poisson Sampling.
  65101. */
  65102. set: function (value) {
  65103. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65104. return;
  65105. }
  65106. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65107. },
  65108. enumerable: true,
  65109. configurable: true
  65110. });
  65111. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65112. /**
  65113. * Gets if the current filter is set to VSM.
  65114. * DEPRECATED. Should use useExponentialShadowMap instead.
  65115. */
  65116. get: function () {
  65117. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65118. return this.useExponentialShadowMap;
  65119. },
  65120. /**
  65121. * Sets the current filter is to VSM.
  65122. * DEPRECATED. Should use useExponentialShadowMap instead.
  65123. */
  65124. set: function (value) {
  65125. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65126. this.useExponentialShadowMap = value;
  65127. },
  65128. enumerable: true,
  65129. configurable: true
  65130. });
  65131. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65132. /**
  65133. * Gets if the current filter is set to blurred VSM.
  65134. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65135. */
  65136. get: function () {
  65137. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65138. return this.useBlurExponentialShadowMap;
  65139. },
  65140. /**
  65141. * Sets the current filter is to blurred VSM.
  65142. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65143. */
  65144. set: function (value) {
  65145. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65146. this.useBlurExponentialShadowMap = value;
  65147. },
  65148. enumerable: true,
  65149. configurable: true
  65150. });
  65151. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65152. /**
  65153. * Gets if the current filter is set to ESM.
  65154. */
  65155. get: function () {
  65156. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65157. },
  65158. /**
  65159. * Sets the current filter is to ESM.
  65160. */
  65161. set: function (value) {
  65162. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65163. return;
  65164. }
  65165. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65166. },
  65167. enumerable: true,
  65168. configurable: true
  65169. });
  65170. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65171. /**
  65172. * Gets if the current filter is set to filtered ESM.
  65173. */
  65174. get: function () {
  65175. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65176. },
  65177. /**
  65178. * Gets if the current filter is set to filtered ESM.
  65179. */
  65180. set: function (value) {
  65181. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65182. return;
  65183. }
  65184. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65185. },
  65186. enumerable: true,
  65187. configurable: true
  65188. });
  65189. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65190. /**
  65191. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65192. * exponential to prevent steep falloff artifacts).
  65193. */
  65194. get: function () {
  65195. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65196. },
  65197. /**
  65198. * Sets the current filter to "close ESM" (using the inverse of the
  65199. * exponential to prevent steep falloff artifacts).
  65200. */
  65201. set: function (value) {
  65202. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65203. return;
  65204. }
  65205. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65206. },
  65207. enumerable: true,
  65208. configurable: true
  65209. });
  65210. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65211. /**
  65212. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65213. * exponential to prevent steep falloff artifacts).
  65214. */
  65215. get: function () {
  65216. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65217. },
  65218. /**
  65219. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65220. * exponential to prevent steep falloff artifacts).
  65221. */
  65222. set: function (value) {
  65223. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65224. return;
  65225. }
  65226. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65227. },
  65228. enumerable: true,
  65229. configurable: true
  65230. });
  65231. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65232. /**
  65233. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65234. */
  65235. get: function () {
  65236. return this.filter === ShadowGenerator.FILTER_PCF;
  65237. },
  65238. /**
  65239. * Sets the current filter to "PCF" (percentage closer filtering).
  65240. */
  65241. set: function (value) {
  65242. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65243. return;
  65244. }
  65245. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65246. },
  65247. enumerable: true,
  65248. configurable: true
  65249. });
  65250. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65251. /**
  65252. * Gets the PCF or PCSS Quality.
  65253. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65254. */
  65255. get: function () {
  65256. return this._filteringQuality;
  65257. },
  65258. /**
  65259. * Sets the PCF or PCSS Quality.
  65260. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65261. */
  65262. set: function (filteringQuality) {
  65263. this._filteringQuality = filteringQuality;
  65264. },
  65265. enumerable: true,
  65266. configurable: true
  65267. });
  65268. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65269. /**
  65270. * Gets if the current filter is set to "PCSS" (contact hardening).
  65271. */
  65272. get: function () {
  65273. return this.filter === ShadowGenerator.FILTER_PCSS;
  65274. },
  65275. /**
  65276. * Sets the current filter to "PCSS" (contact hardening).
  65277. */
  65278. set: function (value) {
  65279. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65280. return;
  65281. }
  65282. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65283. },
  65284. enumerable: true,
  65285. configurable: true
  65286. });
  65287. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65288. /**
  65289. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65290. * Using a ratio helps keeping shape stability independently of the map size.
  65291. *
  65292. * It does not account for the light projection as it was having too much
  65293. * instability during the light setup or during light position changes.
  65294. *
  65295. * Only valid if useContactHardeningShadow is true.
  65296. */
  65297. get: function () {
  65298. return this._contactHardeningLightSizeUVRatio;
  65299. },
  65300. /**
  65301. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65302. * Using a ratio helps keeping shape stability independently of the map size.
  65303. *
  65304. * It does not account for the light projection as it was having too much
  65305. * instability during the light setup or during light position changes.
  65306. *
  65307. * Only valid if useContactHardeningShadow is true.
  65308. */
  65309. set: function (contactHardeningLightSizeUVRatio) {
  65310. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65311. },
  65312. enumerable: true,
  65313. configurable: true
  65314. });
  65315. /**
  65316. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65317. * 0 means strongest and 1 would means no shadow.
  65318. * @returns the darkness.
  65319. */
  65320. ShadowGenerator.prototype.getDarkness = function () {
  65321. return this._darkness;
  65322. };
  65323. /**
  65324. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65325. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65326. * @returns the shadow generator allowing fluent coding.
  65327. */
  65328. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65329. if (darkness >= 1.0)
  65330. this._darkness = 1.0;
  65331. else if (darkness <= 0.0)
  65332. this._darkness = 0.0;
  65333. else
  65334. this._darkness = darkness;
  65335. return this;
  65336. };
  65337. /**
  65338. * Sets the ability to have transparent shadow (boolean).
  65339. * @param transparent True if transparent else False
  65340. * @returns the shadow generator allowing fluent coding
  65341. */
  65342. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65343. this._transparencyShadow = transparent;
  65344. return this;
  65345. };
  65346. /**
  65347. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65348. * @returns The render target texture if present otherwise, null
  65349. */
  65350. ShadowGenerator.prototype.getShadowMap = function () {
  65351. return this._shadowMap;
  65352. };
  65353. /**
  65354. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65355. * @returns The render target texture if the shadow map is present otherwise, null
  65356. */
  65357. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65358. if (this._shadowMap2) {
  65359. return this._shadowMap2;
  65360. }
  65361. return this._shadowMap;
  65362. };
  65363. /**
  65364. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65365. * @param mesh Mesh to add
  65366. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65367. * @returns the Shadow Generator itself
  65368. */
  65369. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65370. if (includeDescendants === void 0) { includeDescendants = true; }
  65371. if (!this._shadowMap) {
  65372. return this;
  65373. }
  65374. if (!this._shadowMap.renderList) {
  65375. this._shadowMap.renderList = [];
  65376. }
  65377. this._shadowMap.renderList.push(mesh);
  65378. if (includeDescendants) {
  65379. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65380. }
  65381. return this;
  65382. var _a;
  65383. };
  65384. /**
  65385. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65386. * @param mesh Mesh to remove
  65387. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65388. * @returns the Shadow Generator itself
  65389. */
  65390. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65391. if (includeDescendants === void 0) { includeDescendants = true; }
  65392. if (!this._shadowMap || !this._shadowMap.renderList) {
  65393. return this;
  65394. }
  65395. var index = this._shadowMap.renderList.indexOf(mesh);
  65396. if (index !== -1) {
  65397. this._shadowMap.renderList.splice(index, 1);
  65398. }
  65399. if (includeDescendants) {
  65400. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65401. var child = _a[_i];
  65402. this.removeShadowCaster(child);
  65403. }
  65404. }
  65405. return this;
  65406. };
  65407. /**
  65408. * Returns the associated light object.
  65409. * @returns the light generating the shadow
  65410. */
  65411. ShadowGenerator.prototype.getLight = function () {
  65412. return this._light;
  65413. };
  65414. ShadowGenerator.prototype._initializeGenerator = function () {
  65415. this._light._markMeshesAsLightDirty();
  65416. this._initializeShadowMap();
  65417. };
  65418. ShadowGenerator.prototype._initializeShadowMap = function () {
  65419. var _this = this;
  65420. // Render target
  65421. var engine = this._scene.getEngine();
  65422. if (engine.webGLVersion > 1) {
  65423. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65424. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65425. }
  65426. else {
  65427. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65428. }
  65429. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65430. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65431. this._shadowMap.anisotropicFilteringLevel = 1;
  65432. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65433. this._shadowMap.renderParticles = false;
  65434. this._shadowMap.ignoreCameraViewport = true;
  65435. // Record Face Index before render.
  65436. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65437. _this._currentFaceIndex = faceIndex;
  65438. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65439. engine.setColorWrite(false);
  65440. }
  65441. });
  65442. // Custom render function.
  65443. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65444. // Blur if required afer render.
  65445. this._shadowMap.onAfterUnbindObservable.add(function () {
  65446. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65447. engine.setColorWrite(true);
  65448. }
  65449. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65450. return;
  65451. }
  65452. var shadowMap = _this.getShadowMapForRendering();
  65453. if (shadowMap) {
  65454. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65455. }
  65456. });
  65457. // Clear according to the chosen filter.
  65458. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65459. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65460. this._shadowMap.onClearObservable.add(function (engine) {
  65461. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65462. engine.clear(clearOne, false, true, false);
  65463. }
  65464. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65465. engine.clear(clearZero, true, true, false);
  65466. }
  65467. else {
  65468. engine.clear(clearOne, true, true, false);
  65469. }
  65470. });
  65471. };
  65472. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65473. var _this = this;
  65474. var engine = this._scene.getEngine();
  65475. var targetSize = this._mapSize / this.blurScale;
  65476. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65477. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65478. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65479. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65480. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65481. }
  65482. if (this.useKernelBlur) {
  65483. 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);
  65484. this._kernelBlurXPostprocess.width = targetSize;
  65485. this._kernelBlurXPostprocess.height = targetSize;
  65486. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65487. effect.setTexture("textureSampler", _this._shadowMap);
  65488. });
  65489. 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);
  65490. this._kernelBlurXPostprocess.autoClear = false;
  65491. this._kernelBlurYPostprocess.autoClear = false;
  65492. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65493. this._kernelBlurXPostprocess.packedFloat = true;
  65494. this._kernelBlurYPostprocess.packedFloat = true;
  65495. }
  65496. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65497. }
  65498. else {
  65499. 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);
  65500. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65501. effect.setFloat2("screenSize", targetSize, targetSize);
  65502. effect.setTexture("textureSampler", _this._shadowMap);
  65503. });
  65504. this._boxBlurPostprocess.autoClear = false;
  65505. this._blurPostProcesses = [this._boxBlurPostprocess];
  65506. }
  65507. };
  65508. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65509. var index;
  65510. var engine = this._scene.getEngine();
  65511. if (depthOnlySubMeshes.length) {
  65512. engine.setColorWrite(false);
  65513. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65514. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65515. }
  65516. engine.setColorWrite(true);
  65517. }
  65518. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65519. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65520. }
  65521. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65522. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65523. }
  65524. if (this._transparencyShadow) {
  65525. for (index = 0; index < transparentSubMeshes.length; index++) {
  65526. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65527. }
  65528. }
  65529. };
  65530. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65531. var _this = this;
  65532. var mesh = subMesh.getRenderingMesh();
  65533. var scene = this._scene;
  65534. var engine = scene.getEngine();
  65535. var material = subMesh.getMaterial();
  65536. if (!material) {
  65537. return;
  65538. }
  65539. // Culling
  65540. engine.setState(material.backFaceCulling);
  65541. // Managing instances
  65542. var batch = mesh._getInstancesRenderList(subMesh._id);
  65543. if (batch.mustReturn) {
  65544. return;
  65545. }
  65546. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65547. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65548. engine.enableEffect(this._effect);
  65549. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65550. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65551. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65552. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65553. this._effect.setVector3("lightData", this._cachedDirection);
  65554. }
  65555. else {
  65556. this._effect.setVector3("lightData", this._cachedPosition);
  65557. }
  65558. if (scene.activeCamera) {
  65559. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65560. }
  65561. // Alpha test
  65562. if (material && material.needAlphaTesting()) {
  65563. var alphaTexture = material.getAlphaTestTexture();
  65564. if (alphaTexture) {
  65565. this._effect.setTexture("diffuseSampler", alphaTexture);
  65566. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65567. }
  65568. }
  65569. // Bones
  65570. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65571. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65572. }
  65573. // Morph targets
  65574. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65575. if (this.forceBackFacesOnly) {
  65576. engine.setState(true, 0, false, true);
  65577. }
  65578. // Draw
  65579. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65580. if (this.forceBackFacesOnly) {
  65581. engine.setState(true, 0, false, false);
  65582. }
  65583. }
  65584. else {
  65585. // Need to reset refresh rate of the shadowMap
  65586. if (this._shadowMap) {
  65587. this._shadowMap.resetRefreshCounter();
  65588. }
  65589. }
  65590. };
  65591. ShadowGenerator.prototype._applyFilterValues = function () {
  65592. if (!this._shadowMap) {
  65593. return;
  65594. }
  65595. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65596. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65597. }
  65598. else {
  65599. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65600. }
  65601. };
  65602. /**
  65603. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65604. * @param onCompiled Callback triggered at the and of the effects compilation
  65605. * @param options Sets of optional options forcing the compilation with different modes
  65606. */
  65607. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65608. var _this = this;
  65609. var localOptions = __assign({ useInstances: false }, options);
  65610. var shadowMap = this.getShadowMap();
  65611. if (!shadowMap) {
  65612. if (onCompiled) {
  65613. onCompiled(this);
  65614. }
  65615. return;
  65616. }
  65617. var renderList = shadowMap.renderList;
  65618. if (!renderList) {
  65619. if (onCompiled) {
  65620. onCompiled(this);
  65621. }
  65622. return;
  65623. }
  65624. var subMeshes = new Array();
  65625. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65626. var mesh = renderList_1[_i];
  65627. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65628. }
  65629. if (subMeshes.length === 0) {
  65630. if (onCompiled) {
  65631. onCompiled(this);
  65632. }
  65633. return;
  65634. }
  65635. var currentIndex = 0;
  65636. var checkReady = function () {
  65637. if (!_this._scene || !_this._scene.getEngine()) {
  65638. return;
  65639. }
  65640. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65641. currentIndex++;
  65642. if (currentIndex >= subMeshes.length) {
  65643. if (onCompiled) {
  65644. onCompiled(_this);
  65645. }
  65646. return;
  65647. }
  65648. }
  65649. setTimeout(checkReady, 16);
  65650. };
  65651. checkReady();
  65652. };
  65653. /**
  65654. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65655. * @param options Sets of optional options forcing the compilation with different modes
  65656. * @returns A promise that resolves when the compilation completes
  65657. */
  65658. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65659. var _this = this;
  65660. return new Promise(function (resolve) {
  65661. _this.forceCompilation(function () {
  65662. resolve();
  65663. }, options);
  65664. });
  65665. };
  65666. /**
  65667. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65668. * @param subMesh The submesh we want to render in the shadow map
  65669. * @param useInstances Defines wether will draw in the map using instances
  65670. * @returns true if ready otherwise, false
  65671. */
  65672. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65673. var defines = [];
  65674. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65675. defines.push("#define FLOAT");
  65676. }
  65677. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65678. defines.push("#define ESM");
  65679. }
  65680. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  65681. defines.push("#define DEPTHTEXTURE");
  65682. }
  65683. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65684. var mesh = subMesh.getMesh();
  65685. var material = subMesh.getMaterial();
  65686. // Normal bias.
  65687. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65688. attribs.push(BABYLON.VertexBuffer.NormalKind);
  65689. defines.push("#define NORMAL");
  65690. if (mesh.nonUniformScaling) {
  65691. defines.push("#define NONUNIFORMSCALING");
  65692. }
  65693. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65694. defines.push("#define DIRECTIONINLIGHTDATA");
  65695. }
  65696. }
  65697. // Alpha test
  65698. if (material && material.needAlphaTesting()) {
  65699. var alphaTexture = material.getAlphaTestTexture();
  65700. if (alphaTexture) {
  65701. defines.push("#define ALPHATEST");
  65702. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65703. attribs.push(BABYLON.VertexBuffer.UVKind);
  65704. defines.push("#define UV1");
  65705. }
  65706. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65707. if (alphaTexture.coordinatesIndex === 1) {
  65708. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65709. defines.push("#define UV2");
  65710. }
  65711. }
  65712. }
  65713. }
  65714. // Bones
  65715. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65716. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65717. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65718. if (mesh.numBoneInfluencers > 4) {
  65719. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65720. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65721. }
  65722. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65723. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65724. }
  65725. else {
  65726. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65727. }
  65728. // Morph targets
  65729. var manager = mesh.morphTargetManager;
  65730. var morphInfluencers = 0;
  65731. if (manager) {
  65732. if (manager.numInfluencers > 0) {
  65733. defines.push("#define MORPHTARGETS");
  65734. morphInfluencers = manager.numInfluencers;
  65735. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65736. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65737. }
  65738. }
  65739. // Instances
  65740. if (useInstances) {
  65741. defines.push("#define INSTANCES");
  65742. attribs.push("world0");
  65743. attribs.push("world1");
  65744. attribs.push("world2");
  65745. attribs.push("world3");
  65746. }
  65747. // Get correct effect
  65748. var join = defines.join("\n");
  65749. if (this._cachedDefines !== join) {
  65750. this._cachedDefines = join;
  65751. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65752. }
  65753. if (!this._effect.isReady()) {
  65754. return false;
  65755. }
  65756. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65757. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65758. this._initializeBlurRTTAndPostProcesses();
  65759. }
  65760. }
  65761. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65762. return false;
  65763. }
  65764. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65765. return false;
  65766. }
  65767. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65768. return false;
  65769. }
  65770. return true;
  65771. };
  65772. /**
  65773. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65774. * @param defines Defines of the material we want to update
  65775. * @param lightIndex Index of the light in the enabled light list of the material
  65776. */
  65777. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65778. var scene = this._scene;
  65779. var light = this._light;
  65780. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65781. return;
  65782. }
  65783. defines["SHADOW" + lightIndex] = true;
  65784. if (this.useContactHardeningShadow) {
  65785. defines["SHADOWPCSS" + lightIndex] = true;
  65786. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65787. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65788. }
  65789. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65790. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65791. }
  65792. // else default to high.
  65793. }
  65794. if (this.usePercentageCloserFiltering) {
  65795. defines["SHADOWPCF" + lightIndex] = true;
  65796. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65797. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65798. }
  65799. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65800. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65801. }
  65802. // else default to high.
  65803. }
  65804. else if (this.usePoissonSampling) {
  65805. defines["SHADOWPOISSON" + lightIndex] = true;
  65806. }
  65807. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65808. defines["SHADOWESM" + lightIndex] = true;
  65809. }
  65810. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65811. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65812. }
  65813. if (light.needCube()) {
  65814. defines["SHADOWCUBE" + lightIndex] = true;
  65815. }
  65816. };
  65817. /**
  65818. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65819. * defined in the generator but impacting the effect).
  65820. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65821. * @param effect The effect we are binfing the information for
  65822. */
  65823. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65824. var light = this._light;
  65825. var scene = this._scene;
  65826. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65827. return;
  65828. }
  65829. var camera = scene.activeCamera;
  65830. if (!camera) {
  65831. return;
  65832. }
  65833. var shadowMap = this.getShadowMap();
  65834. if (!shadowMap) {
  65835. return;
  65836. }
  65837. if (!light.needCube()) {
  65838. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65839. }
  65840. // Only PCF uses depth stencil texture.
  65841. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65842. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65843. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65844. }
  65845. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65846. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65847. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65848. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65849. }
  65850. else {
  65851. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65852. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65853. }
  65854. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65855. };
  65856. /**
  65857. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65858. * (eq to shadow prjection matrix * light transform matrix)
  65859. * @returns The transform matrix used to create the shadow map
  65860. */
  65861. ShadowGenerator.prototype.getTransformMatrix = function () {
  65862. var scene = this._scene;
  65863. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65864. return this._transformMatrix;
  65865. }
  65866. this._currentRenderID = scene.getRenderId();
  65867. this._currentFaceIndexCache = this._currentFaceIndex;
  65868. var lightPosition = this._light.position;
  65869. if (this._light.computeTransformedInformation()) {
  65870. lightPosition = this._light.transformedPosition;
  65871. }
  65872. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65873. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65874. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65875. }
  65876. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65877. this._cachedPosition.copyFrom(lightPosition);
  65878. this._cachedDirection.copyFrom(this._lightDirection);
  65879. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65880. var shadowMap = this.getShadowMap();
  65881. if (shadowMap) {
  65882. var renderList = shadowMap.renderList;
  65883. if (renderList) {
  65884. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65885. }
  65886. }
  65887. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65888. }
  65889. return this._transformMatrix;
  65890. };
  65891. /**
  65892. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65893. * Cube and 2D textures for instance.
  65894. */
  65895. ShadowGenerator.prototype.recreateShadowMap = function () {
  65896. var shadowMap = this._shadowMap;
  65897. if (!shadowMap) {
  65898. return;
  65899. }
  65900. // Track render list.
  65901. var renderList = shadowMap.renderList;
  65902. // Clean up existing data.
  65903. this._disposeRTTandPostProcesses();
  65904. // Reinitializes.
  65905. this._initializeGenerator();
  65906. // Reaffect the filter to ensure a correct fallback if necessary.
  65907. this.filter = this.filter;
  65908. // Reaffect the filter.
  65909. this._applyFilterValues();
  65910. // Reaffect Render List.
  65911. this._shadowMap.renderList = renderList;
  65912. };
  65913. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65914. if (this._shadowMap2) {
  65915. this._shadowMap2.dispose();
  65916. this._shadowMap2 = null;
  65917. }
  65918. if (this._boxBlurPostprocess) {
  65919. this._boxBlurPostprocess.dispose();
  65920. this._boxBlurPostprocess = null;
  65921. }
  65922. if (this._kernelBlurXPostprocess) {
  65923. this._kernelBlurXPostprocess.dispose();
  65924. this._kernelBlurXPostprocess = null;
  65925. }
  65926. if (this._kernelBlurYPostprocess) {
  65927. this._kernelBlurYPostprocess.dispose();
  65928. this._kernelBlurYPostprocess = null;
  65929. }
  65930. this._blurPostProcesses = [];
  65931. };
  65932. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  65933. if (this._shadowMap) {
  65934. this._shadowMap.dispose();
  65935. this._shadowMap = null;
  65936. }
  65937. this._disposeBlurPostProcesses();
  65938. };
  65939. /**
  65940. * Disposes the ShadowGenerator.
  65941. * Returns nothing.
  65942. */
  65943. ShadowGenerator.prototype.dispose = function () {
  65944. this._disposeRTTandPostProcesses();
  65945. if (this._light) {
  65946. this._light._shadowGenerator = null;
  65947. this._light._markMeshesAsLightDirty();
  65948. }
  65949. };
  65950. /**
  65951. * Serializes the shadow generator setup to a json object.
  65952. * @returns The serialized JSON object
  65953. */
  65954. ShadowGenerator.prototype.serialize = function () {
  65955. var serializationObject = {};
  65956. var shadowMap = this.getShadowMap();
  65957. if (!shadowMap) {
  65958. return serializationObject;
  65959. }
  65960. serializationObject.lightId = this._light.id;
  65961. serializationObject.mapSize = shadowMap.getRenderSize();
  65962. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  65963. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  65964. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65965. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65966. serializationObject.usePoissonSampling = this.usePoissonSampling;
  65967. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  65968. serializationObject.depthScale = this.depthScale;
  65969. serializationObject.darkness = this.getDarkness();
  65970. serializationObject.blurBoxOffset = this.blurBoxOffset;
  65971. serializationObject.blurKernel = this.blurKernel;
  65972. serializationObject.blurScale = this.blurScale;
  65973. serializationObject.useKernelBlur = this.useKernelBlur;
  65974. serializationObject.transparencyShadow = this._transparencyShadow;
  65975. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  65976. serializationObject.bias = this.bias;
  65977. serializationObject.normalBias = this.normalBias;
  65978. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  65979. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  65980. serializationObject.filteringQuality = this.filteringQuality;
  65981. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  65982. serializationObject.renderList = [];
  65983. if (shadowMap.renderList) {
  65984. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  65985. var mesh = shadowMap.renderList[meshIndex];
  65986. serializationObject.renderList.push(mesh.id);
  65987. }
  65988. }
  65989. return serializationObject;
  65990. };
  65991. /**
  65992. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  65993. * @param parsedShadowGenerator The JSON object to parse
  65994. * @param scene The scene to create the shadow map for
  65995. * @returns The parsed shadow generator
  65996. */
  65997. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  65998. //casting to point light, as light is missing the position attr and typescript complains.
  65999. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66000. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66001. var shadowMap = shadowGenerator.getShadowMap();
  66002. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66003. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66004. meshes.forEach(function (mesh) {
  66005. if (!shadowMap) {
  66006. return;
  66007. }
  66008. if (!shadowMap.renderList) {
  66009. shadowMap.renderList = [];
  66010. }
  66011. shadowMap.renderList.push(mesh);
  66012. });
  66013. }
  66014. if (parsedShadowGenerator.usePoissonSampling) {
  66015. shadowGenerator.usePoissonSampling = true;
  66016. }
  66017. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66018. shadowGenerator.useExponentialShadowMap = true;
  66019. }
  66020. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66021. shadowGenerator.useBlurExponentialShadowMap = true;
  66022. }
  66023. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66024. shadowGenerator.useCloseExponentialShadowMap = true;
  66025. }
  66026. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66027. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66028. }
  66029. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66030. shadowGenerator.usePercentageCloserFiltering = true;
  66031. }
  66032. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66033. shadowGenerator.useContactHardeningShadow = true;
  66034. }
  66035. if (parsedShadowGenerator.filteringQuality) {
  66036. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66037. }
  66038. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66039. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66040. }
  66041. // Backward compat
  66042. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66043. shadowGenerator.useExponentialShadowMap = true;
  66044. }
  66045. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66046. shadowGenerator.useBlurExponentialShadowMap = true;
  66047. }
  66048. if (parsedShadowGenerator.depthScale) {
  66049. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66050. }
  66051. if (parsedShadowGenerator.blurScale) {
  66052. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66053. }
  66054. if (parsedShadowGenerator.blurBoxOffset) {
  66055. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66056. }
  66057. if (parsedShadowGenerator.useKernelBlur) {
  66058. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66059. }
  66060. if (parsedShadowGenerator.blurKernel) {
  66061. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66062. }
  66063. if (parsedShadowGenerator.bias !== undefined) {
  66064. shadowGenerator.bias = parsedShadowGenerator.bias;
  66065. }
  66066. if (parsedShadowGenerator.normalBias !== undefined) {
  66067. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66068. }
  66069. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66070. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66071. }
  66072. if (parsedShadowGenerator.darkness) {
  66073. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66074. }
  66075. if (parsedShadowGenerator.transparencyShadow) {
  66076. shadowGenerator.setTransparencyShadow(true);
  66077. }
  66078. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66079. return shadowGenerator;
  66080. };
  66081. /**
  66082. * Shadow generator mode None: no filtering applied.
  66083. */
  66084. ShadowGenerator.FILTER_NONE = 0;
  66085. /**
  66086. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66087. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66088. */
  66089. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66090. /**
  66091. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66092. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66093. */
  66094. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66095. /**
  66096. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66097. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66098. */
  66099. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66100. /**
  66101. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66102. * edge artifacts on steep falloff.
  66103. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66104. */
  66105. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66106. /**
  66107. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66108. * edge artifacts on steep falloff.
  66109. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66110. */
  66111. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66112. /**
  66113. * Shadow generator mode PCF: Percentage Closer Filtering
  66114. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66115. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66116. */
  66117. ShadowGenerator.FILTER_PCF = 6;
  66118. /**
  66119. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66120. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66121. * Contact Hardening
  66122. */
  66123. ShadowGenerator.FILTER_PCSS = 7;
  66124. /**
  66125. * Reserved for PCF and PCSS
  66126. * Highest Quality.
  66127. *
  66128. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66129. *
  66130. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66131. */
  66132. ShadowGenerator.QUALITY_HIGH = 0;
  66133. /**
  66134. * Reserved for PCF and PCSS
  66135. * Good tradeoff for quality/perf cross devices
  66136. *
  66137. * Execute PCF on a 3*3 kernel.
  66138. *
  66139. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66140. */
  66141. ShadowGenerator.QUALITY_MEDIUM = 1;
  66142. /**
  66143. * Reserved for PCF and PCSS
  66144. * The lowest quality but the fastest.
  66145. *
  66146. * Execute PCF on a 1*1 kernel.
  66147. *
  66148. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66149. */
  66150. ShadowGenerator.QUALITY_LOW = 2;
  66151. return ShadowGenerator;
  66152. }());
  66153. BABYLON.ShadowGenerator = ShadowGenerator;
  66154. })(BABYLON || (BABYLON = {}));
  66155. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66156. var BABYLON;
  66157. (function (BABYLON) {
  66158. var DefaultLoadingScreen = /** @class */ (function () {
  66159. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66160. if (_loadingText === void 0) { _loadingText = ""; }
  66161. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66162. var _this = this;
  66163. this._renderingCanvas = _renderingCanvas;
  66164. this._loadingText = _loadingText;
  66165. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66166. // Resize
  66167. this._resizeLoadingUI = function () {
  66168. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66169. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66170. if (!_this._loadingDiv) {
  66171. return;
  66172. }
  66173. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66174. _this._loadingDiv.style.left = canvasRect.left + "px";
  66175. _this._loadingDiv.style.top = canvasRect.top + "px";
  66176. _this._loadingDiv.style.width = canvasRect.width + "px";
  66177. _this._loadingDiv.style.height = canvasRect.height + "px";
  66178. };
  66179. }
  66180. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66181. if (this._loadingDiv) {
  66182. // Do not add a loading screen if there is already one
  66183. return;
  66184. }
  66185. this._loadingDiv = document.createElement("div");
  66186. this._loadingDiv.id = "babylonjsLoadingDiv";
  66187. this._loadingDiv.style.opacity = "0";
  66188. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66189. this._loadingDiv.style.pointerEvents = "none";
  66190. // Loading text
  66191. this._loadingTextDiv = document.createElement("div");
  66192. this._loadingTextDiv.style.position = "absolute";
  66193. this._loadingTextDiv.style.left = "0";
  66194. this._loadingTextDiv.style.top = "50%";
  66195. this._loadingTextDiv.style.marginTop = "80px";
  66196. this._loadingTextDiv.style.width = "100%";
  66197. this._loadingTextDiv.style.height = "20px";
  66198. this._loadingTextDiv.style.fontFamily = "Arial";
  66199. this._loadingTextDiv.style.fontSize = "14px";
  66200. this._loadingTextDiv.style.color = "white";
  66201. this._loadingTextDiv.style.textAlign = "center";
  66202. this._loadingTextDiv.innerHTML = "Loading";
  66203. this._loadingDiv.appendChild(this._loadingTextDiv);
  66204. //set the predefined text
  66205. this._loadingTextDiv.innerHTML = this._loadingText;
  66206. // Generating keyframes
  66207. var style = document.createElement('style');
  66208. style.type = 'text/css';
  66209. 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 }";
  66210. style.innerHTML = keyFrames;
  66211. document.getElementsByTagName('head')[0].appendChild(style);
  66212. // Loading img
  66213. var imgBack = new Image();
  66214. 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";
  66215. imgBack.style.position = "absolute";
  66216. imgBack.style.left = "50%";
  66217. imgBack.style.top = "50%";
  66218. imgBack.style.marginLeft = "-60px";
  66219. imgBack.style.marginTop = "-60px";
  66220. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66221. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66222. imgBack.style.transformOrigin = "50% 50%";
  66223. imgBack.style.webkitTransformOrigin = "50% 50%";
  66224. this._loadingDiv.appendChild(imgBack);
  66225. this._resizeLoadingUI();
  66226. window.addEventListener("resize", this._resizeLoadingUI);
  66227. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66228. document.body.appendChild(this._loadingDiv);
  66229. this._loadingDiv.style.opacity = "1";
  66230. };
  66231. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66232. var _this = this;
  66233. if (!this._loadingDiv) {
  66234. return;
  66235. }
  66236. var onTransitionEnd = function () {
  66237. if (!_this._loadingDiv) {
  66238. return;
  66239. }
  66240. document.body.removeChild(_this._loadingDiv);
  66241. window.removeEventListener("resize", _this._resizeLoadingUI);
  66242. _this._loadingDiv = null;
  66243. };
  66244. this._loadingDiv.style.opacity = "0";
  66245. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66246. };
  66247. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66248. set: function (text) {
  66249. this._loadingText = text;
  66250. if (this._loadingTextDiv) {
  66251. this._loadingTextDiv.innerHTML = this._loadingText;
  66252. }
  66253. },
  66254. enumerable: true,
  66255. configurable: true
  66256. });
  66257. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66258. get: function () {
  66259. return this._loadingDivBackgroundColor;
  66260. },
  66261. set: function (color) {
  66262. this._loadingDivBackgroundColor = color;
  66263. if (!this._loadingDiv) {
  66264. return;
  66265. }
  66266. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66267. },
  66268. enumerable: true,
  66269. configurable: true
  66270. });
  66271. return DefaultLoadingScreen;
  66272. }());
  66273. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66274. })(BABYLON || (BABYLON = {}));
  66275. //# sourceMappingURL=babylon.loadingScreen.js.map
  66276. var BABYLON;
  66277. (function (BABYLON) {
  66278. var SceneLoaderProgressEvent = /** @class */ (function () {
  66279. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66280. this.lengthComputable = lengthComputable;
  66281. this.loaded = loaded;
  66282. this.total = total;
  66283. }
  66284. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66285. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66286. };
  66287. return SceneLoaderProgressEvent;
  66288. }());
  66289. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66290. var SceneLoader = /** @class */ (function () {
  66291. function SceneLoader() {
  66292. }
  66293. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66294. get: function () {
  66295. return 0;
  66296. },
  66297. enumerable: true,
  66298. configurable: true
  66299. });
  66300. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66301. get: function () {
  66302. return 1;
  66303. },
  66304. enumerable: true,
  66305. configurable: true
  66306. });
  66307. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66308. get: function () {
  66309. return 2;
  66310. },
  66311. enumerable: true,
  66312. configurable: true
  66313. });
  66314. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66315. get: function () {
  66316. return 3;
  66317. },
  66318. enumerable: true,
  66319. configurable: true
  66320. });
  66321. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66322. get: function () {
  66323. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66324. },
  66325. set: function (value) {
  66326. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66327. },
  66328. enumerable: true,
  66329. configurable: true
  66330. });
  66331. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66332. get: function () {
  66333. return SceneLoader._ShowLoadingScreen;
  66334. },
  66335. set: function (value) {
  66336. SceneLoader._ShowLoadingScreen = value;
  66337. },
  66338. enumerable: true,
  66339. configurable: true
  66340. });
  66341. Object.defineProperty(SceneLoader, "loggingLevel", {
  66342. get: function () {
  66343. return SceneLoader._loggingLevel;
  66344. },
  66345. set: function (value) {
  66346. SceneLoader._loggingLevel = value;
  66347. },
  66348. enumerable: true,
  66349. configurable: true
  66350. });
  66351. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66352. get: function () {
  66353. return SceneLoader._CleanBoneMatrixWeights;
  66354. },
  66355. set: function (value) {
  66356. SceneLoader._CleanBoneMatrixWeights = value;
  66357. },
  66358. enumerable: true,
  66359. configurable: true
  66360. });
  66361. SceneLoader._getDefaultPlugin = function () {
  66362. return SceneLoader._registeredPlugins[".babylon"];
  66363. };
  66364. SceneLoader._getPluginForExtension = function (extension) {
  66365. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66366. if (registeredPlugin) {
  66367. return registeredPlugin;
  66368. }
  66369. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  66370. return SceneLoader._getDefaultPlugin();
  66371. };
  66372. SceneLoader._getPluginForDirectLoad = function (data) {
  66373. for (var extension in SceneLoader._registeredPlugins) {
  66374. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66375. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66376. return SceneLoader._registeredPlugins[extension];
  66377. }
  66378. }
  66379. return SceneLoader._getDefaultPlugin();
  66380. };
  66381. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66382. if (sceneFilename.name) {
  66383. sceneFilename = sceneFilename.name;
  66384. }
  66385. var queryStringPosition = sceneFilename.indexOf("?");
  66386. if (queryStringPosition !== -1) {
  66387. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66388. }
  66389. var dotPosition = sceneFilename.lastIndexOf(".");
  66390. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66391. return SceneLoader._getPluginForExtension(extension);
  66392. };
  66393. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66394. SceneLoader._getDirectLoad = function (sceneFilename) {
  66395. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66396. return sceneFilename.substr(5);
  66397. }
  66398. return null;
  66399. };
  66400. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66401. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66402. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66403. var plugin;
  66404. if (registeredPlugin.plugin.createPlugin) {
  66405. plugin = registeredPlugin.plugin.createPlugin();
  66406. }
  66407. else {
  66408. plugin = registeredPlugin.plugin;
  66409. }
  66410. var useArrayBuffer = registeredPlugin.isBinary;
  66411. var database;
  66412. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66413. var dataCallback = function (data, responseURL) {
  66414. if (scene.isDisposed) {
  66415. onError("Scene has been disposed");
  66416. return;
  66417. }
  66418. scene.database = database;
  66419. onSuccess(plugin, data, responseURL);
  66420. };
  66421. var request = null;
  66422. var pluginDisposed = false;
  66423. var onDisposeObservable = plugin.onDisposeObservable;
  66424. if (onDisposeObservable) {
  66425. onDisposeObservable.add(function () {
  66426. pluginDisposed = true;
  66427. if (request) {
  66428. request.abort();
  66429. request = null;
  66430. }
  66431. onDispose();
  66432. });
  66433. }
  66434. var manifestChecked = function () {
  66435. if (pluginDisposed) {
  66436. return;
  66437. }
  66438. var url = rootUrl + sceneFilename;
  66439. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66440. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66441. } : undefined, database, useArrayBuffer, function (request, exception) {
  66442. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66443. });
  66444. };
  66445. if (directLoad) {
  66446. dataCallback(directLoad);
  66447. return plugin;
  66448. }
  66449. if (rootUrl.indexOf("file:") === -1) {
  66450. var engine = scene.getEngine();
  66451. var canUseOfflineSupport = engine.enableOfflineSupport;
  66452. if (canUseOfflineSupport) {
  66453. // Also check for exceptions
  66454. var exceptionFound = false;
  66455. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66456. var regex = _a[_i];
  66457. if (regex.test(rootUrl + sceneFilename)) {
  66458. exceptionFound = true;
  66459. break;
  66460. }
  66461. }
  66462. canUseOfflineSupport = !exceptionFound;
  66463. }
  66464. if (canUseOfflineSupport) {
  66465. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66466. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66467. }
  66468. else {
  66469. manifestChecked();
  66470. }
  66471. }
  66472. // Loading file from disk via input file or drag'n'drop
  66473. else {
  66474. var fileOrString = sceneFilename;
  66475. if (fileOrString.name) { // File
  66476. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66477. }
  66478. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66479. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66480. }
  66481. else {
  66482. onError("Unable to find file named " + sceneFilename);
  66483. }
  66484. }
  66485. return plugin;
  66486. };
  66487. // Public functions
  66488. SceneLoader.GetPluginForExtension = function (extension) {
  66489. return SceneLoader._getPluginForExtension(extension).plugin;
  66490. };
  66491. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66492. return !!SceneLoader._registeredPlugins[extension];
  66493. };
  66494. SceneLoader.RegisterPlugin = function (plugin) {
  66495. if (typeof plugin.extensions === "string") {
  66496. var extension = plugin.extensions;
  66497. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66498. plugin: plugin,
  66499. isBinary: false
  66500. };
  66501. }
  66502. else {
  66503. var extensions = plugin.extensions;
  66504. Object.keys(extensions).forEach(function (extension) {
  66505. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66506. plugin: plugin,
  66507. isBinary: extensions[extension].isBinary
  66508. };
  66509. });
  66510. }
  66511. };
  66512. /**
  66513. * Import meshes into a scene
  66514. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66515. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66516. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66517. * @param scene the instance of BABYLON.Scene to append to
  66518. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66519. * @param onProgress a callback with a progress event for each file being loaded
  66520. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66521. * @param pluginExtension the extension used to determine the plugin
  66522. * @returns The loaded plugin
  66523. */
  66524. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66525. if (sceneFilename === void 0) { sceneFilename = ""; }
  66526. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66527. if (onSuccess === void 0) { onSuccess = null; }
  66528. if (onProgress === void 0) { onProgress = null; }
  66529. if (onError === void 0) { onError = null; }
  66530. if (pluginExtension === void 0) { pluginExtension = null; }
  66531. if (!scene) {
  66532. BABYLON.Tools.Error("No scene available to import mesh to");
  66533. return null;
  66534. }
  66535. if (!sceneFilename) {
  66536. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66537. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66538. }
  66539. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66540. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66541. return null;
  66542. }
  66543. var loadingToken = {};
  66544. scene._addPendingData(loadingToken);
  66545. var disposeHandler = function () {
  66546. scene._removePendingData(loadingToken);
  66547. };
  66548. var errorHandler = function (message, exception) {
  66549. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66550. if (onError) {
  66551. onError(scene, errorMessage, exception);
  66552. }
  66553. else {
  66554. BABYLON.Tools.Error(errorMessage);
  66555. // should the exception be thrown?
  66556. }
  66557. disposeHandler();
  66558. };
  66559. var progressHandler = onProgress ? function (event) {
  66560. try {
  66561. onProgress(event);
  66562. }
  66563. catch (e) {
  66564. errorHandler("Error in onProgress callback", e);
  66565. }
  66566. } : undefined;
  66567. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66568. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66569. if (onSuccess) {
  66570. try {
  66571. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66572. }
  66573. catch (e) {
  66574. errorHandler("Error in onSuccess callback", e);
  66575. }
  66576. }
  66577. scene._removePendingData(loadingToken);
  66578. };
  66579. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66580. if (plugin.rewriteRootURL) {
  66581. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66582. }
  66583. if (sceneFilename === "") {
  66584. if (sceneFilename === "") {
  66585. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66586. }
  66587. }
  66588. if (plugin.importMesh) {
  66589. var syncedPlugin = plugin;
  66590. var meshes = new Array();
  66591. var particleSystems = new Array();
  66592. var skeletons = new Array();
  66593. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66594. return;
  66595. }
  66596. scene.loadingPluginName = plugin.name;
  66597. successHandler(meshes, particleSystems, skeletons, []);
  66598. }
  66599. else {
  66600. var asyncedPlugin = plugin;
  66601. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66602. scene.loadingPluginName = plugin.name;
  66603. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66604. }).catch(function (error) {
  66605. errorHandler(error.message, error);
  66606. });
  66607. }
  66608. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66609. };
  66610. /**
  66611. * Import meshes into a scene
  66612. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66613. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66614. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66615. * @param scene the instance of BABYLON.Scene to append to
  66616. * @param onProgress a callback with a progress event for each file being loaded
  66617. * @param pluginExtension the extension used to determine the plugin
  66618. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66619. */
  66620. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66621. if (sceneFilename === void 0) { sceneFilename = ""; }
  66622. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66623. if (onProgress === void 0) { onProgress = null; }
  66624. if (pluginExtension === void 0) { pluginExtension = null; }
  66625. return new Promise(function (resolve, reject) {
  66626. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66627. resolve({
  66628. meshes: meshes,
  66629. particleSystems: particleSystems,
  66630. skeletons: skeletons,
  66631. animationGroups: animationGroups
  66632. });
  66633. }, onProgress, function (scene, message, exception) {
  66634. reject(exception || new Error(message));
  66635. }, pluginExtension);
  66636. });
  66637. };
  66638. /**
  66639. * Load a scene
  66640. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66641. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66642. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66643. * @param onSuccess a callback with the scene when import succeeds
  66644. * @param onProgress a callback with a progress event for each file being loaded
  66645. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66646. * @param pluginExtension the extension used to determine the plugin
  66647. * @returns The loaded plugin
  66648. */
  66649. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66650. if (onSuccess === void 0) { onSuccess = null; }
  66651. if (onProgress === void 0) { onProgress = null; }
  66652. if (onError === void 0) { onError = null; }
  66653. if (pluginExtension === void 0) { pluginExtension = null; }
  66654. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66655. };
  66656. /**
  66657. * Load a scene
  66658. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66659. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66660. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66661. * @param onProgress a callback with a progress event for each file being loaded
  66662. * @param pluginExtension the extension used to determine the plugin
  66663. * @returns The loaded scene
  66664. */
  66665. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66666. if (onProgress === void 0) { onProgress = null; }
  66667. if (pluginExtension === void 0) { pluginExtension = null; }
  66668. return new Promise(function (resolve, reject) {
  66669. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66670. resolve(scene);
  66671. }, onProgress, function (scene, message, exception) {
  66672. reject(exception || new Error(message));
  66673. }, pluginExtension);
  66674. });
  66675. };
  66676. /**
  66677. * Append a scene
  66678. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66679. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66680. * @param scene is the instance of BABYLON.Scene to append to
  66681. * @param onSuccess a callback with the scene when import succeeds
  66682. * @param onProgress a callback with a progress event for each file being loaded
  66683. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66684. * @param pluginExtension the extension used to determine the plugin
  66685. * @returns The loaded plugin
  66686. */
  66687. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66688. if (sceneFilename === void 0) { sceneFilename = ""; }
  66689. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66690. if (onSuccess === void 0) { onSuccess = null; }
  66691. if (onProgress === void 0) { onProgress = null; }
  66692. if (onError === void 0) { onError = null; }
  66693. if (pluginExtension === void 0) { pluginExtension = null; }
  66694. if (!scene) {
  66695. BABYLON.Tools.Error("No scene available to append to");
  66696. return null;
  66697. }
  66698. if (!sceneFilename) {
  66699. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66700. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66701. }
  66702. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66703. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66704. return null;
  66705. }
  66706. if (SceneLoader.ShowLoadingScreen) {
  66707. scene.getEngine().displayLoadingUI();
  66708. }
  66709. var loadingToken = {};
  66710. scene._addPendingData(loadingToken);
  66711. var disposeHandler = function () {
  66712. scene._removePendingData(loadingToken);
  66713. scene.getEngine().hideLoadingUI();
  66714. };
  66715. var errorHandler = function (message, exception) {
  66716. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66717. if (onError) {
  66718. onError(scene, errorMessage, exception);
  66719. }
  66720. else {
  66721. BABYLON.Tools.Error(errorMessage);
  66722. // should the exception be thrown?
  66723. }
  66724. disposeHandler();
  66725. };
  66726. var progressHandler = onProgress ? function (event) {
  66727. try {
  66728. onProgress(event);
  66729. }
  66730. catch (e) {
  66731. errorHandler("Error in onProgress callback", e);
  66732. }
  66733. } : undefined;
  66734. var successHandler = function () {
  66735. if (onSuccess) {
  66736. try {
  66737. onSuccess(scene);
  66738. }
  66739. catch (e) {
  66740. errorHandler("Error in onSuccess callback", e);
  66741. }
  66742. }
  66743. scene._removePendingData(loadingToken);
  66744. };
  66745. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66746. if (sceneFilename === "") {
  66747. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66748. }
  66749. if (plugin.load) {
  66750. var syncedPlugin = plugin;
  66751. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66752. return;
  66753. }
  66754. scene.loadingPluginName = plugin.name;
  66755. successHandler();
  66756. }
  66757. else {
  66758. var asyncedPlugin = plugin;
  66759. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66760. scene.loadingPluginName = plugin.name;
  66761. successHandler();
  66762. }).catch(function (error) {
  66763. errorHandler(error.message, error);
  66764. });
  66765. }
  66766. if (SceneLoader.ShowLoadingScreen) {
  66767. scene.executeWhenReady(function () {
  66768. scene.getEngine().hideLoadingUI();
  66769. });
  66770. }
  66771. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66772. };
  66773. /**
  66774. * Append a scene
  66775. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66776. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66777. * @param scene is the instance of BABYLON.Scene to append to
  66778. * @param onProgress a callback with a progress event for each file being loaded
  66779. * @param pluginExtension the extension used to determine the plugin
  66780. * @returns The given scene
  66781. */
  66782. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66783. if (sceneFilename === void 0) { sceneFilename = ""; }
  66784. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66785. if (onProgress === void 0) { onProgress = null; }
  66786. if (pluginExtension === void 0) { pluginExtension = null; }
  66787. return new Promise(function (resolve, reject) {
  66788. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66789. resolve(scene);
  66790. }, onProgress, function (scene, message, exception) {
  66791. reject(exception || new Error(message));
  66792. }, pluginExtension);
  66793. });
  66794. };
  66795. /**
  66796. * Load a scene into an asset container
  66797. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66798. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66799. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  66800. * @param onSuccess a callback with the scene when import succeeds
  66801. * @param onProgress a callback with a progress event for each file being loaded
  66802. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66803. * @param pluginExtension the extension used to determine the plugin
  66804. * @returns The loaded plugin
  66805. */
  66806. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66807. if (sceneFilename === void 0) { sceneFilename = ""; }
  66808. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66809. if (onSuccess === void 0) { onSuccess = null; }
  66810. if (onProgress === void 0) { onProgress = null; }
  66811. if (onError === void 0) { onError = null; }
  66812. if (pluginExtension === void 0) { pluginExtension = null; }
  66813. if (!scene) {
  66814. BABYLON.Tools.Error("No scene available to load asset container to");
  66815. return null;
  66816. }
  66817. if (!sceneFilename) {
  66818. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66819. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66820. }
  66821. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66822. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66823. return null;
  66824. }
  66825. var loadingToken = {};
  66826. scene._addPendingData(loadingToken);
  66827. var disposeHandler = function () {
  66828. scene._removePendingData(loadingToken);
  66829. };
  66830. var errorHandler = function (message, exception) {
  66831. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66832. if (onError) {
  66833. onError(scene, errorMessage, exception);
  66834. }
  66835. else {
  66836. BABYLON.Tools.Error(errorMessage);
  66837. // should the exception be thrown?
  66838. }
  66839. disposeHandler();
  66840. };
  66841. var progressHandler = onProgress ? function (event) {
  66842. try {
  66843. onProgress(event);
  66844. }
  66845. catch (e) {
  66846. errorHandler("Error in onProgress callback", e);
  66847. }
  66848. } : undefined;
  66849. var successHandler = function (assets) {
  66850. if (onSuccess) {
  66851. try {
  66852. onSuccess(assets);
  66853. }
  66854. catch (e) {
  66855. errorHandler("Error in onSuccess callback", e);
  66856. }
  66857. }
  66858. scene._removePendingData(loadingToken);
  66859. };
  66860. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66861. if (plugin.loadAssetContainer) {
  66862. var syncedPlugin = plugin;
  66863. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66864. if (!assetContainer) {
  66865. return;
  66866. }
  66867. scene.loadingPluginName = plugin.name;
  66868. successHandler(assetContainer);
  66869. }
  66870. else if (plugin.loadAssetContainerAsync) {
  66871. var asyncedPlugin = plugin;
  66872. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66873. scene.loadingPluginName = plugin.name;
  66874. successHandler(assetContainer);
  66875. }).catch(function (error) {
  66876. errorHandler(error.message, error);
  66877. });
  66878. }
  66879. else {
  66880. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66881. }
  66882. if (SceneLoader.ShowLoadingScreen) {
  66883. scene.executeWhenReady(function () {
  66884. scene.getEngine().hideLoadingUI();
  66885. });
  66886. }
  66887. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66888. };
  66889. /**
  66890. * Load a scene into an asset container
  66891. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66892. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66893. * @param scene is the instance of BABYLON.Scene to append to
  66894. * @param onProgress a callback with a progress event for each file being loaded
  66895. * @param pluginExtension the extension used to determine the plugin
  66896. * @returns The loaded asset container
  66897. */
  66898. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66899. if (sceneFilename === void 0) { sceneFilename = ""; }
  66900. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66901. if (onProgress === void 0) { onProgress = null; }
  66902. if (pluginExtension === void 0) { pluginExtension = null; }
  66903. return new Promise(function (resolve, reject) {
  66904. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66905. resolve(assetContainer);
  66906. }, onProgress, function (scene, message, exception) {
  66907. reject(exception || new Error(message));
  66908. }, pluginExtension);
  66909. });
  66910. };
  66911. // Flags
  66912. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66913. SceneLoader._ShowLoadingScreen = true;
  66914. SceneLoader._CleanBoneMatrixWeights = false;
  66915. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66916. // Members
  66917. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66918. SceneLoader._registeredPlugins = {};
  66919. return SceneLoader;
  66920. }());
  66921. BABYLON.SceneLoader = SceneLoader;
  66922. ;
  66923. })(BABYLON || (BABYLON = {}));
  66924. //# sourceMappingURL=babylon.sceneLoader.js.map
  66925. var BABYLON;
  66926. (function (BABYLON) {
  66927. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  66928. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66929. var parsedMaterial = parsedData.materials[index];
  66930. if (parsedMaterial.id === id) {
  66931. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66932. }
  66933. }
  66934. return null;
  66935. };
  66936. var isDescendantOf = function (mesh, names, hierarchyIds) {
  66937. for (var i in names) {
  66938. if (mesh.name === names[i]) {
  66939. hierarchyIds.push(mesh.id);
  66940. return true;
  66941. }
  66942. }
  66943. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  66944. hierarchyIds.push(mesh.id);
  66945. return true;
  66946. }
  66947. return false;
  66948. };
  66949. var logOperation = function (operation, producer) {
  66950. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  66951. };
  66952. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  66953. if (addToScene === void 0) { addToScene = false; }
  66954. var container = new BABYLON.AssetContainer(scene);
  66955. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66956. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66957. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66958. // and avoid problems with multiple concurrent .babylon loads.
  66959. var log = "importScene has failed JSON parse";
  66960. try {
  66961. var parsedData = JSON.parse(data);
  66962. log = "";
  66963. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66964. var index;
  66965. var cache;
  66966. // Lights
  66967. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  66968. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  66969. var parsedLight = parsedData.lights[index];
  66970. var light = BABYLON.Light.Parse(parsedLight, scene);
  66971. if (light) {
  66972. container.lights.push(light);
  66973. log += (index === 0 ? "\n\tLights:" : "");
  66974. log += "\n\t\t" + light.toString(fullDetails);
  66975. }
  66976. }
  66977. }
  66978. // Animations
  66979. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  66980. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  66981. var parsedAnimation = parsedData.animations[index];
  66982. var animation = BABYLON.Animation.Parse(parsedAnimation);
  66983. scene.animations.push(animation);
  66984. container.animations.push(animation);
  66985. log += (index === 0 ? "\n\tAnimations:" : "");
  66986. log += "\n\t\t" + animation.toString(fullDetails);
  66987. }
  66988. }
  66989. // Materials
  66990. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  66991. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66992. var parsedMaterial = parsedData.materials[index];
  66993. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66994. container.materials.push(mat);
  66995. log += (index === 0 ? "\n\tMaterials:" : "");
  66996. log += "\n\t\t" + mat.toString(fullDetails);
  66997. }
  66998. }
  66999. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67000. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67001. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67002. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67003. container.multiMaterials.push(mmat);
  67004. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67005. log += "\n\t\t" + mmat.toString(fullDetails);
  67006. }
  67007. }
  67008. // Morph targets
  67009. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67010. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67011. var managerData = _a[_i];
  67012. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67013. }
  67014. }
  67015. // Skeletons
  67016. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67017. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67018. var parsedSkeleton = parsedData.skeletons[index];
  67019. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67020. container.skeletons.push(skeleton);
  67021. log += (index === 0 ? "\n\tSkeletons:" : "");
  67022. log += "\n\t\t" + skeleton.toString(fullDetails);
  67023. }
  67024. }
  67025. // Geometries
  67026. var geometries = parsedData.geometries;
  67027. if (geometries !== undefined && geometries !== null) {
  67028. var addedGeometry = new Array();
  67029. // Boxes
  67030. var boxes = geometries.boxes;
  67031. if (boxes !== undefined && boxes !== null) {
  67032. for (index = 0, cache = boxes.length; index < cache; index++) {
  67033. var parsedBox = boxes[index];
  67034. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67035. }
  67036. }
  67037. // Spheres
  67038. var spheres = geometries.spheres;
  67039. if (spheres !== undefined && spheres !== null) {
  67040. for (index = 0, cache = spheres.length; index < cache; index++) {
  67041. var parsedSphere = spheres[index];
  67042. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67043. }
  67044. }
  67045. // Cylinders
  67046. var cylinders = geometries.cylinders;
  67047. if (cylinders !== undefined && cylinders !== null) {
  67048. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67049. var parsedCylinder = cylinders[index];
  67050. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67051. }
  67052. }
  67053. // Toruses
  67054. var toruses = geometries.toruses;
  67055. if (toruses !== undefined && toruses !== null) {
  67056. for (index = 0, cache = toruses.length; index < cache; index++) {
  67057. var parsedTorus = toruses[index];
  67058. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67059. }
  67060. }
  67061. // Grounds
  67062. var grounds = geometries.grounds;
  67063. if (grounds !== undefined && grounds !== null) {
  67064. for (index = 0, cache = grounds.length; index < cache; index++) {
  67065. var parsedGround = grounds[index];
  67066. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67067. }
  67068. }
  67069. // Planes
  67070. var planes = geometries.planes;
  67071. if (planes !== undefined && planes !== null) {
  67072. for (index = 0, cache = planes.length; index < cache; index++) {
  67073. var parsedPlane = planes[index];
  67074. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67075. }
  67076. }
  67077. // TorusKnots
  67078. var torusKnots = geometries.torusKnots;
  67079. if (torusKnots !== undefined && torusKnots !== null) {
  67080. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67081. var parsedTorusKnot = torusKnots[index];
  67082. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67083. }
  67084. }
  67085. // VertexData
  67086. var vertexData = geometries.vertexData;
  67087. if (vertexData !== undefined && vertexData !== null) {
  67088. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67089. var parsedVertexData = vertexData[index];
  67090. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67091. }
  67092. }
  67093. addedGeometry.forEach(function (g) {
  67094. if (g) {
  67095. container.geometries.push(g);
  67096. }
  67097. });
  67098. }
  67099. // Transform nodes
  67100. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67101. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67102. var parsedTransformNode = parsedData.transformNodes[index];
  67103. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67104. container.transformNodes.push(node);
  67105. }
  67106. }
  67107. // Meshes
  67108. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67109. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67110. var parsedMesh = parsedData.meshes[index];
  67111. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67112. container.meshes.push(mesh);
  67113. log += (index === 0 ? "\n\tMeshes:" : "");
  67114. log += "\n\t\t" + mesh.toString(fullDetails);
  67115. }
  67116. }
  67117. // Cameras
  67118. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67119. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67120. var parsedCamera = parsedData.cameras[index];
  67121. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67122. container.cameras.push(camera);
  67123. log += (index === 0 ? "\n\tCameras:" : "");
  67124. log += "\n\t\t" + camera.toString(fullDetails);
  67125. }
  67126. }
  67127. // Browsing all the graph to connect the dots
  67128. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67129. var camera = scene.cameras[index];
  67130. if (camera._waitingParentId) {
  67131. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67132. camera._waitingParentId = null;
  67133. }
  67134. }
  67135. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67136. var light_1 = scene.lights[index];
  67137. if (light_1 && light_1._waitingParentId) {
  67138. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67139. light_1._waitingParentId = null;
  67140. }
  67141. }
  67142. // Sounds
  67143. // TODO: add sound
  67144. var loadedSounds = [];
  67145. var loadedSound;
  67146. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67147. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67148. var parsedSound = parsedData.sounds[index];
  67149. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67150. if (!parsedSound.url)
  67151. parsedSound.url = parsedSound.name;
  67152. if (!loadedSounds[parsedSound.url]) {
  67153. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67154. loadedSounds[parsedSound.url] = loadedSound;
  67155. container.sounds.push(loadedSound);
  67156. }
  67157. else {
  67158. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67159. }
  67160. }
  67161. else {
  67162. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67163. }
  67164. }
  67165. }
  67166. loadedSounds = [];
  67167. // Connect parents & children and parse actions
  67168. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67169. var transformNode = scene.transformNodes[index];
  67170. if (transformNode._waitingParentId) {
  67171. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67172. transformNode._waitingParentId = null;
  67173. }
  67174. }
  67175. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67176. var mesh = scene.meshes[index];
  67177. if (mesh._waitingParentId) {
  67178. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67179. mesh._waitingParentId = null;
  67180. }
  67181. if (mesh._waitingActions) {
  67182. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67183. mesh._waitingActions = null;
  67184. }
  67185. }
  67186. // freeze world matrix application
  67187. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67188. var currentMesh = scene.meshes[index];
  67189. if (currentMesh._waitingFreezeWorldMatrix) {
  67190. currentMesh.freezeWorldMatrix();
  67191. currentMesh._waitingFreezeWorldMatrix = null;
  67192. }
  67193. else {
  67194. currentMesh.computeWorldMatrix(true);
  67195. }
  67196. }
  67197. // Particles Systems
  67198. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67199. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67200. var parsedParticleSystem = parsedData.particleSystems[index];
  67201. if (parsedParticleSystem.activeParticleCount) {
  67202. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67203. container.particleSystems.push(ps);
  67204. }
  67205. else {
  67206. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67207. container.particleSystems.push(ps);
  67208. }
  67209. }
  67210. }
  67211. // Lens flares
  67212. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67213. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67214. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67215. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67216. container.lensFlareSystems.push(lf);
  67217. }
  67218. }
  67219. // Shadows
  67220. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67221. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67222. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67223. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67224. container.shadowGenerators.push(sg);
  67225. }
  67226. }
  67227. // Lights exclusions / inclusions
  67228. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67229. var light_2 = scene.lights[index];
  67230. // Excluded check
  67231. if (light_2._excludedMeshesIds.length > 0) {
  67232. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67233. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67234. if (excludedMesh) {
  67235. light_2.excludedMeshes.push(excludedMesh);
  67236. }
  67237. }
  67238. light_2._excludedMeshesIds = [];
  67239. }
  67240. // Included check
  67241. if (light_2._includedOnlyMeshesIds.length > 0) {
  67242. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67243. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67244. if (includedOnlyMesh) {
  67245. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67246. }
  67247. }
  67248. light_2._includedOnlyMeshesIds = [];
  67249. }
  67250. }
  67251. // Effect layers
  67252. if (parsedData.effectLayers) {
  67253. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67254. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67255. container.effectLayers.push(effectLayer);
  67256. }
  67257. }
  67258. // Actions (scene)
  67259. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67260. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67261. }
  67262. if (!addToScene) {
  67263. container.removeAllFromScene();
  67264. }
  67265. }
  67266. catch (err) {
  67267. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67268. if (onError) {
  67269. onError(msg, err);
  67270. }
  67271. else {
  67272. BABYLON.Tools.Log(msg);
  67273. throw err;
  67274. }
  67275. }
  67276. finally {
  67277. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67278. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67279. }
  67280. }
  67281. return container;
  67282. };
  67283. BABYLON.SceneLoader.RegisterPlugin({
  67284. name: "babylon.js",
  67285. extensions: ".babylon",
  67286. canDirectLoad: function (data) {
  67287. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67288. return true;
  67289. }
  67290. return false;
  67291. },
  67292. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67293. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67294. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67295. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67296. // and avoid problems with multiple concurrent .babylon loads.
  67297. var log = "importMesh has failed JSON parse";
  67298. try {
  67299. var parsedData = JSON.parse(data);
  67300. log = "";
  67301. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67302. if (!meshesNames) {
  67303. meshesNames = null;
  67304. }
  67305. else if (!Array.isArray(meshesNames)) {
  67306. meshesNames = [meshesNames];
  67307. }
  67308. var hierarchyIds = new Array();
  67309. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67310. var loadedSkeletonsIds = [];
  67311. var loadedMaterialsIds = [];
  67312. var index;
  67313. var cache;
  67314. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67315. var parsedMesh = parsedData.meshes[index];
  67316. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67317. if (meshesNames !== null) {
  67318. // Remove found mesh name from list.
  67319. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67320. }
  67321. //Geometry?
  67322. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67323. //does the file contain geometries?
  67324. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67325. //find the correct geometry and add it to the scene
  67326. var found = false;
  67327. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67328. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67329. return;
  67330. }
  67331. else {
  67332. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67333. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67334. switch (geometryType) {
  67335. case "boxes":
  67336. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67337. break;
  67338. case "spheres":
  67339. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67340. break;
  67341. case "cylinders":
  67342. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67343. break;
  67344. case "toruses":
  67345. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67346. break;
  67347. case "grounds":
  67348. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67349. break;
  67350. case "planes":
  67351. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67352. break;
  67353. case "torusKnots":
  67354. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67355. break;
  67356. case "vertexData":
  67357. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67358. break;
  67359. }
  67360. found = true;
  67361. }
  67362. });
  67363. }
  67364. });
  67365. if (found === false) {
  67366. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67367. }
  67368. }
  67369. }
  67370. // Material ?
  67371. if (parsedMesh.materialId) {
  67372. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67373. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67374. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67375. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67376. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67377. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67378. var subMatId = parsedMultiMaterial.materials[matIndex];
  67379. loadedMaterialsIds.push(subMatId);
  67380. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67381. if (mat) {
  67382. log += "\n\tMaterial " + mat.toString(fullDetails);
  67383. }
  67384. }
  67385. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67386. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67387. if (mmat) {
  67388. materialFound = true;
  67389. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67390. }
  67391. break;
  67392. }
  67393. }
  67394. }
  67395. if (materialFound === false) {
  67396. loadedMaterialsIds.push(parsedMesh.materialId);
  67397. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67398. if (!mat) {
  67399. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67400. }
  67401. else {
  67402. log += "\n\tMaterial " + mat.toString(fullDetails);
  67403. }
  67404. }
  67405. }
  67406. // Skeleton ?
  67407. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67408. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67409. if (skeletonAlreadyLoaded === false) {
  67410. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67411. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67412. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67413. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67414. skeletons.push(skeleton);
  67415. loadedSkeletonsIds.push(parsedSkeleton.id);
  67416. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67417. }
  67418. }
  67419. }
  67420. }
  67421. // Morph targets ?
  67422. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67423. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67424. var managerData = _a[_i];
  67425. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67426. }
  67427. }
  67428. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67429. meshes.push(mesh);
  67430. log += "\n\tMesh " + mesh.toString(fullDetails);
  67431. }
  67432. }
  67433. // Connecting parents
  67434. var currentMesh;
  67435. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67436. currentMesh = scene.meshes[index];
  67437. if (currentMesh._waitingParentId) {
  67438. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67439. currentMesh._waitingParentId = null;
  67440. }
  67441. }
  67442. // freeze and compute world matrix application
  67443. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67444. currentMesh = scene.meshes[index];
  67445. if (currentMesh._waitingFreezeWorldMatrix) {
  67446. currentMesh.freezeWorldMatrix();
  67447. currentMesh._waitingFreezeWorldMatrix = null;
  67448. }
  67449. else {
  67450. currentMesh.computeWorldMatrix(true);
  67451. }
  67452. }
  67453. }
  67454. // Particles
  67455. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67456. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67457. var parsedParticleSystem = parsedData.particleSystems[index];
  67458. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67459. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67460. }
  67461. }
  67462. }
  67463. return true;
  67464. }
  67465. catch (err) {
  67466. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67467. if (onError) {
  67468. onError(msg, err);
  67469. }
  67470. else {
  67471. BABYLON.Tools.Log(msg);
  67472. throw err;
  67473. }
  67474. }
  67475. finally {
  67476. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67477. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67478. }
  67479. }
  67480. return false;
  67481. },
  67482. load: function (scene, data, rootUrl, onError) {
  67483. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67484. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67485. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67486. // and avoid problems with multiple concurrent .babylon loads.
  67487. var log = "importScene has failed JSON parse";
  67488. try {
  67489. var parsedData = JSON.parse(data);
  67490. log = "";
  67491. // Scene
  67492. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67493. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67494. }
  67495. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67496. scene.autoClear = parsedData.autoClear;
  67497. }
  67498. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67499. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67500. }
  67501. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67502. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67503. }
  67504. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67505. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67506. }
  67507. // Fog
  67508. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67509. scene.fogMode = parsedData.fogMode;
  67510. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67511. scene.fogStart = parsedData.fogStart;
  67512. scene.fogEnd = parsedData.fogEnd;
  67513. scene.fogDensity = parsedData.fogDensity;
  67514. log += "\tFog mode for scene: ";
  67515. switch (scene.fogMode) {
  67516. // getters not compiling, so using hardcoded
  67517. case 1:
  67518. log += "exp\n";
  67519. break;
  67520. case 2:
  67521. log += "exp2\n";
  67522. break;
  67523. case 3:
  67524. log += "linear\n";
  67525. break;
  67526. }
  67527. }
  67528. //Physics
  67529. if (parsedData.physicsEnabled) {
  67530. var physicsPlugin;
  67531. if (parsedData.physicsEngine === "cannon") {
  67532. physicsPlugin = new BABYLON.CannonJSPlugin();
  67533. }
  67534. else if (parsedData.physicsEngine === "oimo") {
  67535. physicsPlugin = new BABYLON.OimoJSPlugin();
  67536. }
  67537. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67538. //else - default engine, which is currently oimo
  67539. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67540. scene.enablePhysics(physicsGravity, physicsPlugin);
  67541. }
  67542. // Metadata
  67543. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67544. scene.metadata = parsedData.metadata;
  67545. }
  67546. //collisions, if defined. otherwise, default is true
  67547. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67548. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67549. }
  67550. scene.workerCollisions = !!parsedData.workerCollisions;
  67551. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67552. if (!container) {
  67553. return false;
  67554. }
  67555. if (parsedData.autoAnimate) {
  67556. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67557. }
  67558. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67559. scene.setActiveCameraByID(parsedData.activeCameraID);
  67560. }
  67561. // Environment texture
  67562. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67563. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  67564. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  67565. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  67566. if (parsedData.environmentTextureRotationY) {
  67567. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  67568. }
  67569. scene.environmentTexture = hdrTexture;
  67570. }
  67571. else {
  67572. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67573. if (parsedData.environmentTextureRotationY) {
  67574. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  67575. }
  67576. scene.environmentTexture = cubeTexture;
  67577. }
  67578. if (parsedData.createDefaultSkybox === true) {
  67579. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67580. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67581. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67582. }
  67583. }
  67584. // Finish
  67585. return true;
  67586. }
  67587. catch (err) {
  67588. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67589. if (onError) {
  67590. onError(msg, err);
  67591. }
  67592. else {
  67593. BABYLON.Tools.Log(msg);
  67594. throw err;
  67595. }
  67596. }
  67597. finally {
  67598. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67599. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67600. }
  67601. }
  67602. return false;
  67603. },
  67604. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67605. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67606. return container;
  67607. }
  67608. });
  67609. })(BABYLON || (BABYLON = {}));
  67610. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67611. var BABYLON;
  67612. (function (BABYLON) {
  67613. var FilesInput = /** @class */ (function () {
  67614. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67615. this.onProcessFileCallback = function () { return true; };
  67616. this._engine = engine;
  67617. this._currentScene = scene;
  67618. this._sceneLoadedCallback = sceneLoadedCallback;
  67619. this._progressCallback = progressCallback;
  67620. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67621. this._textureLoadingCallback = textureLoadingCallback;
  67622. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67623. this._onReloadCallback = onReloadCallback;
  67624. this._errorCallback = errorCallback;
  67625. }
  67626. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67627. var _this = this;
  67628. if (elementToMonitor) {
  67629. this._elementToMonitor = elementToMonitor;
  67630. this._dragEnterHandler = function (e) { _this.drag(e); };
  67631. this._dragOverHandler = function (e) { _this.drag(e); };
  67632. this._dropHandler = function (e) { _this.drop(e); };
  67633. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67634. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67635. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67636. }
  67637. };
  67638. FilesInput.prototype.dispose = function () {
  67639. if (!this._elementToMonitor) {
  67640. return;
  67641. }
  67642. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67643. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67644. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67645. };
  67646. FilesInput.prototype.renderFunction = function () {
  67647. if (this._additionalRenderLoopLogicCallback) {
  67648. this._additionalRenderLoopLogicCallback();
  67649. }
  67650. if (this._currentScene) {
  67651. if (this._textureLoadingCallback) {
  67652. var remaining = this._currentScene.getWaitingItemsCount();
  67653. if (remaining > 0) {
  67654. this._textureLoadingCallback(remaining);
  67655. }
  67656. }
  67657. this._currentScene.render();
  67658. }
  67659. };
  67660. FilesInput.prototype.drag = function (e) {
  67661. e.stopPropagation();
  67662. e.preventDefault();
  67663. };
  67664. FilesInput.prototype.drop = function (eventDrop) {
  67665. eventDrop.stopPropagation();
  67666. eventDrop.preventDefault();
  67667. this.loadFiles(eventDrop);
  67668. };
  67669. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67670. var _this = this;
  67671. var reader = folder.createReader();
  67672. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67673. reader.readEntries(function (entries) {
  67674. remaining.count += entries.length;
  67675. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67676. var entry = entries_1[_i];
  67677. if (entry.isFile) {
  67678. entry.file(function (file) {
  67679. file.correctName = relativePath + file.name;
  67680. files.push(file);
  67681. if (--remaining.count === 0) {
  67682. callback();
  67683. }
  67684. });
  67685. }
  67686. else if (entry.isDirectory) {
  67687. _this._traverseFolder(entry, files, remaining, callback);
  67688. }
  67689. }
  67690. if (--remaining.count) {
  67691. callback();
  67692. }
  67693. });
  67694. };
  67695. FilesInput.prototype._processFiles = function (files) {
  67696. for (var i = 0; i < files.length; i++) {
  67697. var name = files[i].correctName.toLowerCase();
  67698. var extension = name.split('.').pop();
  67699. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67700. continue;
  67701. }
  67702. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67703. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67704. this._sceneFileToLoad = files[i];
  67705. }
  67706. else {
  67707. FilesInput.FilesToLoad[name] = files[i];
  67708. }
  67709. }
  67710. };
  67711. FilesInput.prototype.loadFiles = function (event) {
  67712. var _this = this;
  67713. if (this._startingProcessingFilesCallback)
  67714. this._startingProcessingFilesCallback();
  67715. // Handling data transfer via drag'n'drop
  67716. if (event && event.dataTransfer && event.dataTransfer.files) {
  67717. this._filesToLoad = event.dataTransfer.files;
  67718. }
  67719. // Handling files from input files
  67720. if (event && event.target && event.target.files) {
  67721. this._filesToLoad = event.target.files;
  67722. }
  67723. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67724. var files_1 = new Array();
  67725. var folders = [];
  67726. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67727. for (var i = 0; i < this._filesToLoad.length; i++) {
  67728. var fileToLoad = this._filesToLoad[i];
  67729. var name_1 = fileToLoad.name.toLowerCase();
  67730. var entry = void 0;
  67731. fileToLoad.correctName = name_1;
  67732. if (items) {
  67733. var item = items[i];
  67734. if (item.getAsEntry) {
  67735. entry = item.getAsEntry();
  67736. }
  67737. else if (item.webkitGetAsEntry) {
  67738. entry = item.webkitGetAsEntry();
  67739. }
  67740. }
  67741. if (!entry) {
  67742. files_1.push(fileToLoad);
  67743. }
  67744. else {
  67745. if (entry.isDirectory) {
  67746. folders.push(entry);
  67747. }
  67748. else {
  67749. files_1.push(fileToLoad);
  67750. }
  67751. }
  67752. }
  67753. if (folders.length === 0) {
  67754. this._processFiles(files_1);
  67755. this._processReload();
  67756. }
  67757. else {
  67758. var remaining = { count: folders.length };
  67759. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  67760. var folder = folders_1[_i];
  67761. this._traverseFolder(folder, files_1, remaining, function () {
  67762. _this._processFiles(files_1);
  67763. if (remaining.count === 0) {
  67764. _this._processReload();
  67765. }
  67766. });
  67767. }
  67768. }
  67769. }
  67770. };
  67771. FilesInput.prototype._processReload = function () {
  67772. if (this._onReloadCallback) {
  67773. this._onReloadCallback(this._sceneFileToLoad);
  67774. }
  67775. else {
  67776. this.reload();
  67777. }
  67778. };
  67779. FilesInput.prototype.reload = function () {
  67780. var _this = this;
  67781. // If a scene file has been provided
  67782. if (this._sceneFileToLoad) {
  67783. if (this._currentScene) {
  67784. if (BABYLON.Tools.errorsCount > 0) {
  67785. BABYLON.Tools.ClearLogCache();
  67786. }
  67787. this._engine.stopRenderLoop();
  67788. }
  67789. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67790. if (_this._progressCallback) {
  67791. _this._progressCallback(progress);
  67792. }
  67793. }).then(function (scene) {
  67794. if (_this._currentScene) {
  67795. _this._currentScene.dispose();
  67796. }
  67797. _this._currentScene = scene;
  67798. if (_this._sceneLoadedCallback) {
  67799. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67800. }
  67801. // Wait for textures and shaders to be ready
  67802. _this._currentScene.executeWhenReady(function () {
  67803. _this._engine.runRenderLoop(function () {
  67804. _this.renderFunction();
  67805. });
  67806. });
  67807. }).catch(function (error) {
  67808. if (_this._errorCallback) {
  67809. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67810. }
  67811. });
  67812. }
  67813. else {
  67814. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67815. }
  67816. };
  67817. FilesInput.FilesToLoad = {};
  67818. return FilesInput;
  67819. }());
  67820. BABYLON.FilesInput = FilesInput;
  67821. })(BABYLON || (BABYLON = {}));
  67822. //# sourceMappingURL=babylon.filesInput.js.map
  67823. var BABYLON;
  67824. (function (BABYLON) {
  67825. /**
  67826. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67827. * The underlying implementation relies on an associative array to ensure the best performances.
  67828. * The value can be anything including 'null' but except 'undefined'
  67829. */
  67830. var StringDictionary = /** @class */ (function () {
  67831. function StringDictionary() {
  67832. this._count = 0;
  67833. this._data = {};
  67834. }
  67835. /**
  67836. * This will clear this dictionary and copy the content from the 'source' one.
  67837. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67838. * @param source the dictionary to take the content from and copy to this dictionary
  67839. */
  67840. StringDictionary.prototype.copyFrom = function (source) {
  67841. var _this = this;
  67842. this.clear();
  67843. source.forEach(function (t, v) { return _this.add(t, v); });
  67844. };
  67845. /**
  67846. * Get a value based from its key
  67847. * @param key the given key to get the matching value from
  67848. * @return the value if found, otherwise undefined is returned
  67849. */
  67850. StringDictionary.prototype.get = function (key) {
  67851. var val = this._data[key];
  67852. if (val !== undefined) {
  67853. return val;
  67854. }
  67855. return undefined;
  67856. };
  67857. /**
  67858. * Get a value from its key or add it if it doesn't exist.
  67859. * This method will ensure you that a given key/data will be present in the dictionary.
  67860. * @param key the given key to get the matching value from
  67861. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67862. * The factory will only be invoked if there's no data for the given key.
  67863. * @return the value corresponding to the key.
  67864. */
  67865. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67866. var val = this.get(key);
  67867. if (val !== undefined) {
  67868. return val;
  67869. }
  67870. val = factory(key);
  67871. if (val) {
  67872. this.add(key, val);
  67873. }
  67874. return val;
  67875. };
  67876. /**
  67877. * Get a value from its key if present in the dictionary otherwise add it
  67878. * @param key the key to get the value from
  67879. * @param val if there's no such key/value pair in the dictionary add it with this value
  67880. * @return the value corresponding to the key
  67881. */
  67882. StringDictionary.prototype.getOrAdd = function (key, val) {
  67883. var curVal = this.get(key);
  67884. if (curVal !== undefined) {
  67885. return curVal;
  67886. }
  67887. this.add(key, val);
  67888. return val;
  67889. };
  67890. /**
  67891. * Check if there's a given key in the dictionary
  67892. * @param key the key to check for
  67893. * @return true if the key is present, false otherwise
  67894. */
  67895. StringDictionary.prototype.contains = function (key) {
  67896. return this._data[key] !== undefined;
  67897. };
  67898. /**
  67899. * Add a new key and its corresponding value
  67900. * @param key the key to add
  67901. * @param value the value corresponding to the key
  67902. * @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
  67903. */
  67904. StringDictionary.prototype.add = function (key, value) {
  67905. if (this._data[key] !== undefined) {
  67906. return false;
  67907. }
  67908. this._data[key] = value;
  67909. ++this._count;
  67910. return true;
  67911. };
  67912. StringDictionary.prototype.set = function (key, value) {
  67913. if (this._data[key] === undefined) {
  67914. return false;
  67915. }
  67916. this._data[key] = value;
  67917. return true;
  67918. };
  67919. /**
  67920. * Get the element of the given key and remove it from the dictionary
  67921. * @param key
  67922. */
  67923. StringDictionary.prototype.getAndRemove = function (key) {
  67924. var val = this.get(key);
  67925. if (val !== undefined) {
  67926. delete this._data[key];
  67927. --this._count;
  67928. return val;
  67929. }
  67930. return null;
  67931. };
  67932. /**
  67933. * Remove a key/value from the dictionary.
  67934. * @param key the key to remove
  67935. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  67936. */
  67937. StringDictionary.prototype.remove = function (key) {
  67938. if (this.contains(key)) {
  67939. delete this._data[key];
  67940. --this._count;
  67941. return true;
  67942. }
  67943. return false;
  67944. };
  67945. /**
  67946. * Clear the whole content of the dictionary
  67947. */
  67948. StringDictionary.prototype.clear = function () {
  67949. this._data = {};
  67950. this._count = 0;
  67951. };
  67952. Object.defineProperty(StringDictionary.prototype, "count", {
  67953. get: function () {
  67954. return this._count;
  67955. },
  67956. enumerable: true,
  67957. configurable: true
  67958. });
  67959. /**
  67960. * Execute a callback on each key/val of the dictionary.
  67961. * Note that you can remove any element in this dictionary in the callback implementation
  67962. * @param callback the callback to execute on a given key/value pair
  67963. */
  67964. StringDictionary.prototype.forEach = function (callback) {
  67965. for (var cur in this._data) {
  67966. var val = this._data[cur];
  67967. callback(cur, val);
  67968. }
  67969. };
  67970. /**
  67971. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  67972. * If the callback returns null or undefined the method will iterate to the next key/value pair
  67973. * Note that you can remove any element in this dictionary in the callback implementation
  67974. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  67975. */
  67976. StringDictionary.prototype.first = function (callback) {
  67977. for (var cur in this._data) {
  67978. var val = this._data[cur];
  67979. var res = callback(cur, val);
  67980. if (res) {
  67981. return res;
  67982. }
  67983. }
  67984. return null;
  67985. };
  67986. return StringDictionary;
  67987. }());
  67988. BABYLON.StringDictionary = StringDictionary;
  67989. })(BABYLON || (BABYLON = {}));
  67990. //# sourceMappingURL=babylon.stringDictionary.js.map
  67991. var BABYLON;
  67992. (function (BABYLON) {
  67993. var Tags = /** @class */ (function () {
  67994. function Tags() {
  67995. }
  67996. Tags.EnableFor = function (obj) {
  67997. obj._tags = obj._tags || {};
  67998. obj.hasTags = function () {
  67999. return Tags.HasTags(obj);
  68000. };
  68001. obj.addTags = function (tagsString) {
  68002. return Tags.AddTagsTo(obj, tagsString);
  68003. };
  68004. obj.removeTags = function (tagsString) {
  68005. return Tags.RemoveTagsFrom(obj, tagsString);
  68006. };
  68007. obj.matchesTagsQuery = function (tagsQuery) {
  68008. return Tags.MatchesQuery(obj, tagsQuery);
  68009. };
  68010. };
  68011. Tags.DisableFor = function (obj) {
  68012. delete obj._tags;
  68013. delete obj.hasTags;
  68014. delete obj.addTags;
  68015. delete obj.removeTags;
  68016. delete obj.matchesTagsQuery;
  68017. };
  68018. Tags.HasTags = function (obj) {
  68019. if (!obj._tags) {
  68020. return false;
  68021. }
  68022. return !BABYLON.Tools.IsEmpty(obj._tags);
  68023. };
  68024. Tags.GetTags = function (obj, asString) {
  68025. if (asString === void 0) { asString = true; }
  68026. if (!obj._tags) {
  68027. return null;
  68028. }
  68029. if (asString) {
  68030. var tagsArray = [];
  68031. for (var tag in obj._tags) {
  68032. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68033. tagsArray.push(tag);
  68034. }
  68035. }
  68036. return tagsArray.join(" ");
  68037. }
  68038. else {
  68039. return obj._tags;
  68040. }
  68041. };
  68042. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68043. // a tag cannot start with '||', '&&', and '!'
  68044. // it cannot contain whitespaces
  68045. Tags.AddTagsTo = function (obj, tagsString) {
  68046. if (!tagsString) {
  68047. return;
  68048. }
  68049. if (typeof tagsString !== "string") {
  68050. return;
  68051. }
  68052. var tags = tagsString.split(" ");
  68053. tags.forEach(function (tag, index, array) {
  68054. Tags._AddTagTo(obj, tag);
  68055. });
  68056. };
  68057. Tags._AddTagTo = function (obj, tag) {
  68058. tag = tag.trim();
  68059. if (tag === "" || tag === "true" || tag === "false") {
  68060. return;
  68061. }
  68062. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68063. return;
  68064. }
  68065. Tags.EnableFor(obj);
  68066. obj._tags[tag] = true;
  68067. };
  68068. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68069. if (!Tags.HasTags(obj)) {
  68070. return;
  68071. }
  68072. var tags = tagsString.split(" ");
  68073. for (var t in tags) {
  68074. Tags._RemoveTagFrom(obj, tags[t]);
  68075. }
  68076. };
  68077. Tags._RemoveTagFrom = function (obj, tag) {
  68078. delete obj._tags[tag];
  68079. };
  68080. Tags.MatchesQuery = function (obj, tagsQuery) {
  68081. if (tagsQuery === undefined) {
  68082. return true;
  68083. }
  68084. if (tagsQuery === "") {
  68085. return Tags.HasTags(obj);
  68086. }
  68087. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68088. };
  68089. return Tags;
  68090. }());
  68091. BABYLON.Tags = Tags;
  68092. })(BABYLON || (BABYLON = {}));
  68093. //# sourceMappingURL=babylon.tags.js.map
  68094. var BABYLON;
  68095. (function (BABYLON) {
  68096. /**
  68097. * Class used to evalaute queries containing `and` and `or` operators
  68098. */
  68099. var AndOrNotEvaluator = /** @class */ (function () {
  68100. function AndOrNotEvaluator() {
  68101. }
  68102. /**
  68103. * Evaluate a query
  68104. * @param query defines the query to evaluate
  68105. * @param evaluateCallback defines the callback used to filter result
  68106. * @returns true if the query matches
  68107. */
  68108. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68109. if (!query.match(/\([^\(\)]*\)/g)) {
  68110. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68111. }
  68112. else {
  68113. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68114. // remove parenthesis
  68115. r = r.slice(1, r.length - 1);
  68116. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68117. });
  68118. }
  68119. if (query === "true") {
  68120. return true;
  68121. }
  68122. if (query === "false") {
  68123. return false;
  68124. }
  68125. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68126. };
  68127. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68128. evaluateCallback = evaluateCallback || (function (r) {
  68129. return r === "true" ? true : false;
  68130. });
  68131. var result;
  68132. var or = parenthesisContent.split("||");
  68133. for (var i in or) {
  68134. if (or.hasOwnProperty(i)) {
  68135. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68136. var and = ori.split("&&");
  68137. if (and.length > 1) {
  68138. for (var j = 0; j < and.length; ++j) {
  68139. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68140. if (andj !== "true" && andj !== "false") {
  68141. if (andj[0] === "!") {
  68142. result = !evaluateCallback(andj.substring(1));
  68143. }
  68144. else {
  68145. result = evaluateCallback(andj);
  68146. }
  68147. }
  68148. else {
  68149. result = andj === "true" ? true : false;
  68150. }
  68151. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68152. ori = "false";
  68153. break;
  68154. }
  68155. }
  68156. }
  68157. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68158. result = true;
  68159. break;
  68160. }
  68161. // result equals false (or undefined)
  68162. if (ori !== "true" && ori !== "false") {
  68163. if (ori[0] === "!") {
  68164. result = !evaluateCallback(ori.substring(1));
  68165. }
  68166. else {
  68167. result = evaluateCallback(ori);
  68168. }
  68169. }
  68170. else {
  68171. result = ori === "true" ? true : false;
  68172. }
  68173. }
  68174. }
  68175. // the whole parenthesis scope is replaced by 'true' or 'false'
  68176. return result ? "true" : "false";
  68177. };
  68178. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68179. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68180. // remove whitespaces
  68181. r = r.replace(/[\s]/g, function () { return ""; });
  68182. return r.length % 2 ? "!" : "";
  68183. });
  68184. booleanString = booleanString.trim();
  68185. if (booleanString === "!true") {
  68186. booleanString = "false";
  68187. }
  68188. else if (booleanString === "!false") {
  68189. booleanString = "true";
  68190. }
  68191. return booleanString;
  68192. };
  68193. return AndOrNotEvaluator;
  68194. }());
  68195. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68196. })(BABYLON || (BABYLON = {}));
  68197. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68198. var BABYLON;
  68199. (function (BABYLON) {
  68200. /**
  68201. * Class used to enable access to IndexedDB
  68202. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68203. */
  68204. var Database = /** @class */ (function () {
  68205. /**
  68206. * Creates a new Database
  68207. * @param urlToScene defines the url to load the scene
  68208. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68209. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68210. */
  68211. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68212. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68213. var _this = this;
  68214. // Handling various flavors of prefixed version of IndexedDB
  68215. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68216. this.callbackManifestChecked = callbackManifestChecked;
  68217. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68218. this.db = null;
  68219. this._enableSceneOffline = false;
  68220. this._enableTexturesOffline = false;
  68221. this.manifestVersionFound = 0;
  68222. this.mustUpdateRessources = false;
  68223. this.hasReachedQuota = false;
  68224. if (!Database.IDBStorageEnabled) {
  68225. this.callbackManifestChecked(true);
  68226. }
  68227. else {
  68228. if (disableManifestCheck) {
  68229. this._enableSceneOffline = true;
  68230. this._enableTexturesOffline = true;
  68231. this.manifestVersionFound = 1;
  68232. BABYLON.Tools.SetImmediate(function () {
  68233. _this.callbackManifestChecked(true);
  68234. });
  68235. }
  68236. else {
  68237. this._checkManifestFile();
  68238. }
  68239. }
  68240. }
  68241. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68242. /**
  68243. * Gets a boolean indicating if scene must be saved in the database
  68244. */
  68245. get: function () {
  68246. return this._enableSceneOffline;
  68247. },
  68248. enumerable: true,
  68249. configurable: true
  68250. });
  68251. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68252. /**
  68253. * Gets a boolean indicating if textures must be saved in the database
  68254. */
  68255. get: function () {
  68256. return this._enableTexturesOffline;
  68257. },
  68258. enumerable: true,
  68259. configurable: true
  68260. });
  68261. Database.prototype._checkManifestFile = function () {
  68262. var _this = this;
  68263. var noManifestFile = function () {
  68264. _this._enableSceneOffline = false;
  68265. _this._enableTexturesOffline = false;
  68266. _this.callbackManifestChecked(false);
  68267. };
  68268. var timeStampUsed = false;
  68269. var manifestURL = this.currentSceneUrl + ".manifest";
  68270. var xhr = new XMLHttpRequest();
  68271. if (navigator.onLine) {
  68272. // Adding a timestamp to by-pass browsers' cache
  68273. timeStampUsed = true;
  68274. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68275. }
  68276. xhr.open("GET", manifestURL, true);
  68277. xhr.addEventListener("load", function () {
  68278. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68279. try {
  68280. var manifestFile = JSON.parse(xhr.response);
  68281. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68282. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68283. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68284. _this.manifestVersionFound = manifestFile.version;
  68285. }
  68286. if (_this.callbackManifestChecked) {
  68287. _this.callbackManifestChecked(true);
  68288. }
  68289. }
  68290. catch (ex) {
  68291. noManifestFile();
  68292. }
  68293. }
  68294. else {
  68295. noManifestFile();
  68296. }
  68297. }, false);
  68298. xhr.addEventListener("error", function (event) {
  68299. if (timeStampUsed) {
  68300. timeStampUsed = false;
  68301. // Let's retry without the timeStamp
  68302. // It could fail when coupled with HTML5 Offline API
  68303. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68304. xhr.open("GET", retryManifestURL, true);
  68305. xhr.send();
  68306. }
  68307. else {
  68308. noManifestFile();
  68309. }
  68310. }, false);
  68311. try {
  68312. xhr.send();
  68313. }
  68314. catch (ex) {
  68315. BABYLON.Tools.Error("Error on XHR send request.");
  68316. this.callbackManifestChecked(false);
  68317. }
  68318. };
  68319. /**
  68320. * Open the database and make it available
  68321. * @param successCallback defines the callback to call on success
  68322. * @param errorCallback defines the callback to call on error
  68323. */
  68324. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68325. var _this = this;
  68326. var handleError = function () {
  68327. _this.isSupported = false;
  68328. if (errorCallback)
  68329. errorCallback();
  68330. };
  68331. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68332. // Your browser doesn't support IndexedDB
  68333. this.isSupported = false;
  68334. if (errorCallback)
  68335. errorCallback();
  68336. }
  68337. else {
  68338. // If the DB hasn't been opened or created yet
  68339. if (!this.db) {
  68340. this.hasReachedQuota = false;
  68341. this.isSupported = true;
  68342. var request = this.idbFactory.open("babylonjs", 1);
  68343. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68344. request.onerror = function (event) {
  68345. handleError();
  68346. };
  68347. // executes when a version change transaction cannot complete due to other active transactions
  68348. request.onblocked = function (event) {
  68349. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68350. handleError();
  68351. };
  68352. // DB has been opened successfully
  68353. request.onsuccess = function (event) {
  68354. _this.db = request.result;
  68355. successCallback();
  68356. };
  68357. // Initialization of the DB. Creating Scenes & Textures stores
  68358. request.onupgradeneeded = function (event) {
  68359. _this.db = (event.target).result;
  68360. if (_this.db) {
  68361. try {
  68362. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68363. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68364. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68365. }
  68366. catch (ex) {
  68367. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68368. handleError();
  68369. }
  68370. }
  68371. };
  68372. }
  68373. // DB has already been created and opened
  68374. else {
  68375. if (successCallback)
  68376. successCallback();
  68377. }
  68378. }
  68379. };
  68380. /**
  68381. * Loads an image from the database
  68382. * @param url defines the url to load from
  68383. * @param image defines the target DOM image
  68384. */
  68385. Database.prototype.loadImageFromDB = function (url, image) {
  68386. var _this = this;
  68387. var completeURL = Database._ReturnFullUrlLocation(url);
  68388. var saveAndLoadImage = function () {
  68389. if (!_this.hasReachedQuota && _this.db !== null) {
  68390. // the texture is not yet in the DB, let's try to save it
  68391. _this._saveImageIntoDBAsync(completeURL, image);
  68392. }
  68393. // If the texture is not in the DB and we've reached the DB quota limit
  68394. // let's load it directly from the web
  68395. else {
  68396. image.src = url;
  68397. }
  68398. };
  68399. if (!this.mustUpdateRessources) {
  68400. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68401. }
  68402. // First time we're download the images or update requested in the manifest file by a version change
  68403. else {
  68404. saveAndLoadImage();
  68405. }
  68406. };
  68407. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68408. if (this.isSupported && this.db !== null) {
  68409. var texture;
  68410. var transaction = this.db.transaction(["textures"]);
  68411. transaction.onabort = function (event) {
  68412. image.src = url;
  68413. };
  68414. transaction.oncomplete = function (event) {
  68415. var blobTextureURL;
  68416. if (texture) {
  68417. var URL = window.URL || window.webkitURL;
  68418. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68419. image.onerror = function () {
  68420. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68421. image.src = url;
  68422. };
  68423. image.src = blobTextureURL;
  68424. }
  68425. else {
  68426. notInDBCallback();
  68427. }
  68428. };
  68429. var getRequest = transaction.objectStore("textures").get(url);
  68430. getRequest.onsuccess = function (event) {
  68431. texture = (event.target).result;
  68432. };
  68433. getRequest.onerror = function (event) {
  68434. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68435. image.src = url;
  68436. };
  68437. }
  68438. else {
  68439. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68440. image.src = url;
  68441. }
  68442. };
  68443. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68444. var _this = this;
  68445. if (this.isSupported) {
  68446. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68447. var generateBlobUrl = function () {
  68448. var blobTextureURL;
  68449. if (blob) {
  68450. var URL = window.URL || window.webkitURL;
  68451. try {
  68452. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68453. }
  68454. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68455. catch (ex) {
  68456. blobTextureURL = URL.createObjectURL(blob);
  68457. }
  68458. }
  68459. if (blobTextureURL) {
  68460. image.src = blobTextureURL;
  68461. }
  68462. };
  68463. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68464. var xhr = new XMLHttpRequest(), blob;
  68465. xhr.open("GET", url, true);
  68466. xhr.responseType = "blob";
  68467. xhr.addEventListener("load", function () {
  68468. if (xhr.status === 200 && _this.db) {
  68469. // Blob as response (XHR2)
  68470. blob = xhr.response;
  68471. var transaction = _this.db.transaction(["textures"], "readwrite");
  68472. // the transaction could abort because of a QuotaExceededError error
  68473. transaction.onabort = function (event) {
  68474. try {
  68475. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68476. var srcElement = (event.srcElement || event.target);
  68477. var error = srcElement.error;
  68478. if (error && error.name === "QuotaExceededError") {
  68479. _this.hasReachedQuota = true;
  68480. }
  68481. }
  68482. catch (ex) { }
  68483. generateBlobUrl();
  68484. };
  68485. transaction.oncomplete = function (event) {
  68486. generateBlobUrl();
  68487. };
  68488. var newTexture = { textureUrl: url, data: blob };
  68489. try {
  68490. // Put the blob into the dabase
  68491. var addRequest = transaction.objectStore("textures").put(newTexture);
  68492. addRequest.onsuccess = function (event) {
  68493. };
  68494. addRequest.onerror = function (event) {
  68495. generateBlobUrl();
  68496. };
  68497. }
  68498. catch (ex) {
  68499. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68500. if (ex.code === 25) {
  68501. Database.IsUASupportingBlobStorage = false;
  68502. }
  68503. image.src = url;
  68504. }
  68505. }
  68506. else {
  68507. image.src = url;
  68508. }
  68509. }, false);
  68510. xhr.addEventListener("error", function (event) {
  68511. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68512. image.src = url;
  68513. }, false);
  68514. xhr.send();
  68515. }
  68516. else {
  68517. image.src = url;
  68518. }
  68519. }
  68520. else {
  68521. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68522. image.src = url;
  68523. }
  68524. };
  68525. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68526. var _this = this;
  68527. var updateVersion = function () {
  68528. // the version is not yet in the DB or we need to update it
  68529. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68530. };
  68531. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68532. };
  68533. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68534. var _this = this;
  68535. if (this.isSupported && this.db) {
  68536. var version;
  68537. try {
  68538. var transaction = this.db.transaction(["versions"]);
  68539. transaction.oncomplete = function (event) {
  68540. if (version) {
  68541. // If the version in the JSON file is different from the version in DB
  68542. if (_this.manifestVersionFound !== version.data) {
  68543. _this.mustUpdateRessources = true;
  68544. updateInDBCallback();
  68545. }
  68546. else {
  68547. callback(version.data);
  68548. }
  68549. }
  68550. // version was not found in DB
  68551. else {
  68552. _this.mustUpdateRessources = true;
  68553. updateInDBCallback();
  68554. }
  68555. };
  68556. transaction.onabort = function (event) {
  68557. callback(-1);
  68558. };
  68559. var getRequest = transaction.objectStore("versions").get(url);
  68560. getRequest.onsuccess = function (event) {
  68561. version = (event.target).result;
  68562. };
  68563. getRequest.onerror = function (event) {
  68564. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68565. callback(-1);
  68566. };
  68567. }
  68568. catch (ex) {
  68569. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68570. callback(-1);
  68571. }
  68572. }
  68573. else {
  68574. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68575. callback(-1);
  68576. }
  68577. };
  68578. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68579. var _this = this;
  68580. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68581. try {
  68582. // Open a transaction to the database
  68583. var transaction = this.db.transaction(["versions"], "readwrite");
  68584. // the transaction could abort because of a QuotaExceededError error
  68585. transaction.onabort = function (event) {
  68586. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68587. var error = event.srcElement['error'];
  68588. if (error && error.name === "QuotaExceededError") {
  68589. _this.hasReachedQuota = true;
  68590. }
  68591. }
  68592. catch (ex) { }
  68593. callback(-1);
  68594. };
  68595. transaction.oncomplete = function (event) {
  68596. callback(_this.manifestVersionFound);
  68597. };
  68598. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68599. // Put the scene into the database
  68600. var addRequest = transaction.objectStore("versions").put(newVersion);
  68601. addRequest.onsuccess = function (event) {
  68602. };
  68603. addRequest.onerror = function (event) {
  68604. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68605. };
  68606. }
  68607. catch (ex) {
  68608. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68609. callback(-1);
  68610. }
  68611. }
  68612. else {
  68613. callback(-1);
  68614. }
  68615. };
  68616. /**
  68617. * Loads a file from database
  68618. * @param url defines the URL to load from
  68619. * @param sceneLoaded defines a callback to call on success
  68620. * @param progressCallBack defines a callback to call when progress changed
  68621. * @param errorCallback defines a callback to call on error
  68622. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  68623. */
  68624. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68625. var _this = this;
  68626. var completeUrl = Database._ReturnFullUrlLocation(url);
  68627. var saveAndLoadFile = function () {
  68628. // the scene is not yet in the DB, let's try to save it
  68629. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68630. };
  68631. this._checkVersionFromDB(completeUrl, function (version) {
  68632. if (version !== -1) {
  68633. if (!_this.mustUpdateRessources) {
  68634. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68635. }
  68636. else {
  68637. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68638. }
  68639. }
  68640. else {
  68641. if (errorCallback) {
  68642. errorCallback();
  68643. }
  68644. }
  68645. });
  68646. };
  68647. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68648. if (this.isSupported && this.db) {
  68649. var targetStore;
  68650. if (url.indexOf(".babylon") !== -1) {
  68651. targetStore = "scenes";
  68652. }
  68653. else {
  68654. targetStore = "textures";
  68655. }
  68656. var file;
  68657. var transaction = this.db.transaction([targetStore]);
  68658. transaction.oncomplete = function (event) {
  68659. if (file) {
  68660. callback(file.data);
  68661. }
  68662. // file was not found in DB
  68663. else {
  68664. notInDBCallback();
  68665. }
  68666. };
  68667. transaction.onabort = function (event) {
  68668. notInDBCallback();
  68669. };
  68670. var getRequest = transaction.objectStore(targetStore).get(url);
  68671. getRequest.onsuccess = function (event) {
  68672. file = (event.target).result;
  68673. };
  68674. getRequest.onerror = function (event) {
  68675. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68676. notInDBCallback();
  68677. };
  68678. }
  68679. else {
  68680. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68681. callback();
  68682. }
  68683. };
  68684. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68685. var _this = this;
  68686. if (this.isSupported) {
  68687. var targetStore;
  68688. if (url.indexOf(".babylon") !== -1) {
  68689. targetStore = "scenes";
  68690. }
  68691. else {
  68692. targetStore = "textures";
  68693. }
  68694. // Create XHR
  68695. var xhr = new XMLHttpRequest();
  68696. var fileData;
  68697. xhr.open("GET", url, true);
  68698. if (useArrayBuffer) {
  68699. xhr.responseType = "arraybuffer";
  68700. }
  68701. if (progressCallback) {
  68702. xhr.onprogress = progressCallback;
  68703. }
  68704. xhr.addEventListener("load", function () {
  68705. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68706. // Blob as response (XHR2)
  68707. //fileData = xhr.responseText;
  68708. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68709. if (!_this.hasReachedQuota && _this.db) {
  68710. // Open a transaction to the database
  68711. var transaction = _this.db.transaction([targetStore], "readwrite");
  68712. // the transaction could abort because of a QuotaExceededError error
  68713. transaction.onabort = function (event) {
  68714. try {
  68715. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68716. var error = event.srcElement['error'];
  68717. if (error && error.name === "QuotaExceededError") {
  68718. _this.hasReachedQuota = true;
  68719. }
  68720. }
  68721. catch (ex) { }
  68722. callback(fileData);
  68723. };
  68724. transaction.oncomplete = function (event) {
  68725. callback(fileData);
  68726. };
  68727. var newFile;
  68728. if (targetStore === "scenes") {
  68729. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68730. }
  68731. else {
  68732. newFile = { textureUrl: url, data: fileData };
  68733. }
  68734. try {
  68735. // Put the scene into the database
  68736. var addRequest = transaction.objectStore(targetStore).put(newFile);
  68737. addRequest.onsuccess = function (event) {
  68738. };
  68739. addRequest.onerror = function (event) {
  68740. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  68741. };
  68742. }
  68743. catch (ex) {
  68744. callback(fileData);
  68745. }
  68746. }
  68747. else {
  68748. callback(fileData);
  68749. }
  68750. }
  68751. else {
  68752. callback();
  68753. }
  68754. }, false);
  68755. xhr.addEventListener("error", function (event) {
  68756. BABYLON.Tools.Error("error on XHR request.");
  68757. callback();
  68758. }, false);
  68759. xhr.send();
  68760. }
  68761. else {
  68762. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68763. callback();
  68764. }
  68765. };
  68766. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  68767. Database.IsUASupportingBlobStorage = true;
  68768. /** Gets a boolean indicating if Database storate is enabled */
  68769. Database.IDBStorageEnabled = true;
  68770. Database._ParseURL = function (url) {
  68771. var a = document.createElement('a');
  68772. a.href = url;
  68773. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  68774. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  68775. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  68776. return absLocation;
  68777. };
  68778. Database._ReturnFullUrlLocation = function (url) {
  68779. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  68780. return (Database._ParseURL(window.location.href) + url);
  68781. }
  68782. else {
  68783. return url;
  68784. }
  68785. };
  68786. return Database;
  68787. }());
  68788. BABYLON.Database = Database;
  68789. })(BABYLON || (BABYLON = {}));
  68790. //# sourceMappingURL=babylon.database.js.map
  68791. var BABYLON;
  68792. (function (BABYLON) {
  68793. var FresnelParameters = /** @class */ (function () {
  68794. function FresnelParameters() {
  68795. this._isEnabled = true;
  68796. this.leftColor = BABYLON.Color3.White();
  68797. this.rightColor = BABYLON.Color3.Black();
  68798. this.bias = 0;
  68799. this.power = 1;
  68800. }
  68801. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  68802. get: function () {
  68803. return this._isEnabled;
  68804. },
  68805. set: function (value) {
  68806. if (this._isEnabled === value) {
  68807. return;
  68808. }
  68809. this._isEnabled = value;
  68810. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  68811. },
  68812. enumerable: true,
  68813. configurable: true
  68814. });
  68815. FresnelParameters.prototype.clone = function () {
  68816. var newFresnelParameters = new FresnelParameters();
  68817. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  68818. return newFresnelParameters;
  68819. };
  68820. FresnelParameters.prototype.serialize = function () {
  68821. var serializationObject = {};
  68822. serializationObject.isEnabled = this.isEnabled;
  68823. serializationObject.leftColor = this.leftColor.asArray();
  68824. serializationObject.rightColor = this.rightColor.asArray();
  68825. serializationObject.bias = this.bias;
  68826. serializationObject.power = this.power;
  68827. return serializationObject;
  68828. };
  68829. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68830. var fresnelParameters = new FresnelParameters();
  68831. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68832. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68833. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68834. fresnelParameters.bias = parsedFresnelParameters.bias;
  68835. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68836. return fresnelParameters;
  68837. };
  68838. return FresnelParameters;
  68839. }());
  68840. BABYLON.FresnelParameters = FresnelParameters;
  68841. })(BABYLON || (BABYLON = {}));
  68842. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68843. var BABYLON;
  68844. (function (BABYLON) {
  68845. var MultiMaterial = /** @class */ (function (_super) {
  68846. __extends(MultiMaterial, _super);
  68847. function MultiMaterial(name, scene) {
  68848. var _this = _super.call(this, name, scene, true) || this;
  68849. scene.multiMaterials.push(_this);
  68850. _this.subMaterials = new Array();
  68851. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68852. return _this;
  68853. }
  68854. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68855. get: function () {
  68856. return this._subMaterials;
  68857. },
  68858. set: function (value) {
  68859. this._subMaterials = value;
  68860. this._hookArray(value);
  68861. },
  68862. enumerable: true,
  68863. configurable: true
  68864. });
  68865. MultiMaterial.prototype._hookArray = function (array) {
  68866. var _this = this;
  68867. var oldPush = array.push;
  68868. array.push = function () {
  68869. var items = [];
  68870. for (var _i = 0; _i < arguments.length; _i++) {
  68871. items[_i] = arguments[_i];
  68872. }
  68873. var result = oldPush.apply(array, items);
  68874. _this._markAllSubMeshesAsTexturesDirty();
  68875. return result;
  68876. };
  68877. var oldSplice = array.splice;
  68878. array.splice = function (index, deleteCount) {
  68879. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68880. _this._markAllSubMeshesAsTexturesDirty();
  68881. return deleted;
  68882. };
  68883. };
  68884. // Properties
  68885. MultiMaterial.prototype.getSubMaterial = function (index) {
  68886. if (index < 0 || index >= this.subMaterials.length) {
  68887. return this.getScene().defaultMaterial;
  68888. }
  68889. return this.subMaterials[index];
  68890. };
  68891. MultiMaterial.prototype.getActiveTextures = function () {
  68892. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68893. if (subMaterial) {
  68894. return subMaterial.getActiveTextures();
  68895. }
  68896. else {
  68897. return [];
  68898. }
  68899. }));
  68900. var _a;
  68901. };
  68902. // Methods
  68903. MultiMaterial.prototype.getClassName = function () {
  68904. return "MultiMaterial";
  68905. };
  68906. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68907. for (var index = 0; index < this.subMaterials.length; index++) {
  68908. var subMaterial = this.subMaterials[index];
  68909. if (subMaterial) {
  68910. if (subMaterial.storeEffectOnSubMeshes) {
  68911. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68912. return false;
  68913. }
  68914. continue;
  68915. }
  68916. if (!subMaterial.isReady(mesh)) {
  68917. return false;
  68918. }
  68919. }
  68920. }
  68921. return true;
  68922. };
  68923. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68924. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  68925. for (var index = 0; index < this.subMaterials.length; index++) {
  68926. var subMaterial = null;
  68927. var current = this.subMaterials[index];
  68928. if (cloneChildren && current) {
  68929. subMaterial = current.clone(name + "-" + current.name);
  68930. }
  68931. else {
  68932. subMaterial = this.subMaterials[index];
  68933. }
  68934. newMultiMaterial.subMaterials.push(subMaterial);
  68935. }
  68936. return newMultiMaterial;
  68937. };
  68938. MultiMaterial.prototype.serialize = function () {
  68939. var serializationObject = {};
  68940. serializationObject.name = this.name;
  68941. serializationObject.id = this.id;
  68942. if (BABYLON.Tags) {
  68943. serializationObject.tags = BABYLON.Tags.GetTags(this);
  68944. }
  68945. serializationObject.materials = [];
  68946. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  68947. var subMat = this.subMaterials[matIndex];
  68948. if (subMat) {
  68949. serializationObject.materials.push(subMat.id);
  68950. }
  68951. else {
  68952. serializationObject.materials.push(null);
  68953. }
  68954. }
  68955. return serializationObject;
  68956. };
  68957. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  68958. var scene = this.getScene();
  68959. if (!scene) {
  68960. return;
  68961. }
  68962. var index = scene.multiMaterials.indexOf(this);
  68963. if (index >= 0) {
  68964. scene.multiMaterials.splice(index, 1);
  68965. }
  68966. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  68967. };
  68968. return MultiMaterial;
  68969. }(BABYLON.Material));
  68970. BABYLON.MultiMaterial = MultiMaterial;
  68971. })(BABYLON || (BABYLON = {}));
  68972. //# sourceMappingURL=babylon.multiMaterial.js.map
  68973. var BABYLON;
  68974. (function (BABYLON) {
  68975. var FreeCameraTouchInput = /** @class */ (function () {
  68976. function FreeCameraTouchInput() {
  68977. this._offsetX = null;
  68978. this._offsetY = null;
  68979. this._pointerPressed = new Array();
  68980. this.touchAngularSensibility = 200000.0;
  68981. this.touchMoveSensibility = 250.0;
  68982. }
  68983. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  68984. var _this = this;
  68985. var previousPosition = null;
  68986. if (this._pointerInput === undefined) {
  68987. this._onLostFocus = function (evt) {
  68988. _this._offsetX = null;
  68989. _this._offsetY = null;
  68990. };
  68991. this._pointerInput = function (p, s) {
  68992. var evt = p.event;
  68993. if (evt.pointerType === "mouse") {
  68994. return;
  68995. }
  68996. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  68997. if (!noPreventDefault) {
  68998. evt.preventDefault();
  68999. }
  69000. _this._pointerPressed.push(evt.pointerId);
  69001. if (_this._pointerPressed.length !== 1) {
  69002. return;
  69003. }
  69004. previousPosition = {
  69005. x: evt.clientX,
  69006. y: evt.clientY
  69007. };
  69008. }
  69009. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69010. if (!noPreventDefault) {
  69011. evt.preventDefault();
  69012. }
  69013. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69014. if (index === -1) {
  69015. return;
  69016. }
  69017. _this._pointerPressed.splice(index, 1);
  69018. if (index != 0) {
  69019. return;
  69020. }
  69021. previousPosition = null;
  69022. _this._offsetX = null;
  69023. _this._offsetY = null;
  69024. }
  69025. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69026. if (!noPreventDefault) {
  69027. evt.preventDefault();
  69028. }
  69029. if (!previousPosition) {
  69030. return;
  69031. }
  69032. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69033. if (index != 0) {
  69034. return;
  69035. }
  69036. _this._offsetX = evt.clientX - previousPosition.x;
  69037. _this._offsetY = -(evt.clientY - previousPosition.y);
  69038. }
  69039. };
  69040. }
  69041. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69042. if (this._onLostFocus) {
  69043. element.addEventListener("blur", this._onLostFocus);
  69044. }
  69045. };
  69046. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69047. if (this._pointerInput && element) {
  69048. if (this._observer) {
  69049. this.camera.getScene().onPointerObservable.remove(this._observer);
  69050. this._observer = null;
  69051. }
  69052. if (this._onLostFocus) {
  69053. element.removeEventListener("blur", this._onLostFocus);
  69054. this._onLostFocus = null;
  69055. }
  69056. this._pointerPressed = [];
  69057. this._offsetX = null;
  69058. this._offsetY = null;
  69059. }
  69060. };
  69061. FreeCameraTouchInput.prototype.checkInputs = function () {
  69062. if (this._offsetX && this._offsetY) {
  69063. var camera = this.camera;
  69064. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69065. if (this._pointerPressed.length > 1) {
  69066. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69067. }
  69068. else {
  69069. var speed = camera._computeLocalCameraSpeed();
  69070. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69071. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69072. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69073. }
  69074. }
  69075. };
  69076. FreeCameraTouchInput.prototype.getClassName = function () {
  69077. return "FreeCameraTouchInput";
  69078. };
  69079. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69080. return "touch";
  69081. };
  69082. __decorate([
  69083. BABYLON.serialize()
  69084. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69085. __decorate([
  69086. BABYLON.serialize()
  69087. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69088. return FreeCameraTouchInput;
  69089. }());
  69090. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69091. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69092. })(BABYLON || (BABYLON = {}));
  69093. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69094. var BABYLON;
  69095. (function (BABYLON) {
  69096. // We're mainly based on the logic defined into the FreeCamera code
  69097. var TouchCamera = /** @class */ (function (_super) {
  69098. __extends(TouchCamera, _super);
  69099. //-- end properties for backward compatibility for inputs
  69100. function TouchCamera(name, position, scene) {
  69101. var _this = _super.call(this, name, position, scene) || this;
  69102. _this.inputs.addTouch();
  69103. _this._setupInputs();
  69104. return _this;
  69105. }
  69106. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69107. //-- Begin properties for backward compatibility for inputs
  69108. get: function () {
  69109. var touch = this.inputs.attached["touch"];
  69110. if (touch)
  69111. return touch.touchAngularSensibility;
  69112. return 0;
  69113. },
  69114. set: function (value) {
  69115. var touch = this.inputs.attached["touch"];
  69116. if (touch)
  69117. touch.touchAngularSensibility = value;
  69118. },
  69119. enumerable: true,
  69120. configurable: true
  69121. });
  69122. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69123. get: function () {
  69124. var touch = this.inputs.attached["touch"];
  69125. if (touch)
  69126. return touch.touchMoveSensibility;
  69127. return 0;
  69128. },
  69129. set: function (value) {
  69130. var touch = this.inputs.attached["touch"];
  69131. if (touch)
  69132. touch.touchMoveSensibility = value;
  69133. },
  69134. enumerable: true,
  69135. configurable: true
  69136. });
  69137. TouchCamera.prototype.getClassName = function () {
  69138. return "TouchCamera";
  69139. };
  69140. TouchCamera.prototype._setupInputs = function () {
  69141. var mouse = this.inputs.attached["mouse"];
  69142. if (mouse) {
  69143. mouse.touchEnabled = false;
  69144. }
  69145. };
  69146. return TouchCamera;
  69147. }(BABYLON.FreeCamera));
  69148. BABYLON.TouchCamera = TouchCamera;
  69149. })(BABYLON || (BABYLON = {}));
  69150. //# sourceMappingURL=babylon.touchCamera.js.map
  69151. var BABYLON;
  69152. (function (BABYLON) {
  69153. var ProceduralTexture = /** @class */ (function (_super) {
  69154. __extends(ProceduralTexture, _super);
  69155. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69156. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69157. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69158. if (isCube === void 0) { isCube = false; }
  69159. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69160. _this.isCube = isCube;
  69161. _this.isEnabled = true;
  69162. _this._currentRefreshId = -1;
  69163. _this._refreshRate = 1;
  69164. _this._vertexBuffers = {};
  69165. _this._uniforms = new Array();
  69166. _this._samplers = new Array();
  69167. _this._textures = {};
  69168. _this._floats = {};
  69169. _this._floatsArrays = {};
  69170. _this._colors3 = {};
  69171. _this._colors4 = {};
  69172. _this._vectors2 = {};
  69173. _this._vectors3 = {};
  69174. _this._matrices = {};
  69175. _this._fallbackTextureUsed = false;
  69176. scene.proceduralTextures.push(_this);
  69177. _this._engine = scene.getEngine();
  69178. _this.name = name;
  69179. _this.isRenderTarget = true;
  69180. _this._size = size;
  69181. _this._generateMipMaps = generateMipMaps;
  69182. _this.setFragment(fragment);
  69183. _this._fallbackTexture = fallbackTexture;
  69184. if (isCube) {
  69185. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69186. _this.setFloat("face", 0);
  69187. }
  69188. else {
  69189. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69190. }
  69191. // VBO
  69192. var vertices = [];
  69193. vertices.push(1, 1);
  69194. vertices.push(-1, 1);
  69195. vertices.push(-1, -1);
  69196. vertices.push(1, -1);
  69197. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69198. _this._createIndexBuffer();
  69199. return _this;
  69200. }
  69201. ProceduralTexture.prototype._createIndexBuffer = function () {
  69202. var engine = this._engine;
  69203. // Indices
  69204. var indices = [];
  69205. indices.push(0);
  69206. indices.push(1);
  69207. indices.push(2);
  69208. indices.push(0);
  69209. indices.push(2);
  69210. indices.push(3);
  69211. this._indexBuffer = engine.createIndexBuffer(indices);
  69212. };
  69213. ProceduralTexture.prototype._rebuild = function () {
  69214. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69215. if (vb) {
  69216. vb._rebuild();
  69217. }
  69218. this._createIndexBuffer();
  69219. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69220. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69221. }
  69222. };
  69223. ProceduralTexture.prototype.reset = function () {
  69224. if (this._effect === undefined) {
  69225. return;
  69226. }
  69227. var engine = this._engine;
  69228. engine._releaseEffect(this._effect);
  69229. };
  69230. ProceduralTexture.prototype.isReady = function () {
  69231. var _this = this;
  69232. var engine = this._engine;
  69233. var shaders;
  69234. if (!this._fragment) {
  69235. return false;
  69236. }
  69237. if (this._fallbackTextureUsed) {
  69238. return true;
  69239. }
  69240. if (this._fragment.fragmentElement !== undefined) {
  69241. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69242. }
  69243. else {
  69244. shaders = { vertex: "procedural", fragment: this._fragment };
  69245. }
  69246. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69247. _this.releaseInternalTexture();
  69248. if (_this._fallbackTexture) {
  69249. _this._texture = _this._fallbackTexture._texture;
  69250. if (_this._texture) {
  69251. _this._texture.incrementReferences();
  69252. }
  69253. }
  69254. _this._fallbackTextureUsed = true;
  69255. });
  69256. return this._effect.isReady();
  69257. };
  69258. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69259. this._currentRefreshId = -1;
  69260. };
  69261. ProceduralTexture.prototype.setFragment = function (fragment) {
  69262. this._fragment = fragment;
  69263. };
  69264. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69265. get: function () {
  69266. return this._refreshRate;
  69267. },
  69268. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69269. set: function (value) {
  69270. this._refreshRate = value;
  69271. this.resetRefreshCounter();
  69272. },
  69273. enumerable: true,
  69274. configurable: true
  69275. });
  69276. ProceduralTexture.prototype._shouldRender = function () {
  69277. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69278. return false;
  69279. }
  69280. if (this._fallbackTextureUsed) {
  69281. return false;
  69282. }
  69283. if (this._currentRefreshId === -1) { // At least render once
  69284. this._currentRefreshId = 1;
  69285. return true;
  69286. }
  69287. if (this.refreshRate === this._currentRefreshId) {
  69288. this._currentRefreshId = 1;
  69289. return true;
  69290. }
  69291. this._currentRefreshId++;
  69292. return false;
  69293. };
  69294. ProceduralTexture.prototype.getRenderSize = function () {
  69295. return this._size;
  69296. };
  69297. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69298. if (this._fallbackTextureUsed) {
  69299. return;
  69300. }
  69301. this.releaseInternalTexture();
  69302. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69303. // Update properties
  69304. this._size = size;
  69305. this._generateMipMaps = generateMipMaps;
  69306. };
  69307. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69308. if (this._uniforms.indexOf(uniformName) === -1) {
  69309. this._uniforms.push(uniformName);
  69310. }
  69311. };
  69312. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69313. if (this._samplers.indexOf(name) === -1) {
  69314. this._samplers.push(name);
  69315. }
  69316. this._textures[name] = texture;
  69317. return this;
  69318. };
  69319. ProceduralTexture.prototype.setFloat = function (name, value) {
  69320. this._checkUniform(name);
  69321. this._floats[name] = value;
  69322. return this;
  69323. };
  69324. ProceduralTexture.prototype.setFloats = function (name, value) {
  69325. this._checkUniform(name);
  69326. this._floatsArrays[name] = value;
  69327. return this;
  69328. };
  69329. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69330. this._checkUniform(name);
  69331. this._colors3[name] = value;
  69332. return this;
  69333. };
  69334. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69335. this._checkUniform(name);
  69336. this._colors4[name] = value;
  69337. return this;
  69338. };
  69339. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69340. this._checkUniform(name);
  69341. this._vectors2[name] = value;
  69342. return this;
  69343. };
  69344. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69345. this._checkUniform(name);
  69346. this._vectors3[name] = value;
  69347. return this;
  69348. };
  69349. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69350. this._checkUniform(name);
  69351. this._matrices[name] = value;
  69352. return this;
  69353. };
  69354. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69355. var scene = this.getScene();
  69356. if (!scene) {
  69357. return;
  69358. }
  69359. var engine = this._engine;
  69360. // Render
  69361. engine.enableEffect(this._effect);
  69362. engine.setState(false);
  69363. // Texture
  69364. for (var name in this._textures) {
  69365. this._effect.setTexture(name, this._textures[name]);
  69366. }
  69367. // Float
  69368. for (name in this._floats) {
  69369. this._effect.setFloat(name, this._floats[name]);
  69370. }
  69371. // Floats
  69372. for (name in this._floatsArrays) {
  69373. this._effect.setArray(name, this._floatsArrays[name]);
  69374. }
  69375. // Color3
  69376. for (name in this._colors3) {
  69377. this._effect.setColor3(name, this._colors3[name]);
  69378. }
  69379. // Color4
  69380. for (name in this._colors4) {
  69381. var color = this._colors4[name];
  69382. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69383. }
  69384. // Vector2
  69385. for (name in this._vectors2) {
  69386. this._effect.setVector2(name, this._vectors2[name]);
  69387. }
  69388. // Vector3
  69389. for (name in this._vectors3) {
  69390. this._effect.setVector3(name, this._vectors3[name]);
  69391. }
  69392. // Matrix
  69393. for (name in this._matrices) {
  69394. this._effect.setMatrix(name, this._matrices[name]);
  69395. }
  69396. if (!this._texture) {
  69397. return;
  69398. }
  69399. if (this.isCube) {
  69400. for (var face = 0; face < 6; face++) {
  69401. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69402. // VBOs
  69403. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69404. this._effect.setFloat("face", face);
  69405. // Clear
  69406. engine.clear(scene.clearColor, true, true, true);
  69407. // Draw order
  69408. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69409. // Mipmaps
  69410. if (face === 5) {
  69411. engine.generateMipMapsForCubemap(this._texture);
  69412. }
  69413. }
  69414. }
  69415. else {
  69416. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69417. // VBOs
  69418. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69419. // Clear
  69420. engine.clear(scene.clearColor, true, true, true);
  69421. // Draw order
  69422. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69423. }
  69424. // Unbind
  69425. engine.unBindFramebuffer(this._texture, this.isCube);
  69426. if (this.onGenerated) {
  69427. this.onGenerated();
  69428. }
  69429. };
  69430. ProceduralTexture.prototype.clone = function () {
  69431. var textureSize = this.getSize();
  69432. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69433. // Base texture
  69434. newTexture.hasAlpha = this.hasAlpha;
  69435. newTexture.level = this.level;
  69436. // RenderTarget Texture
  69437. newTexture.coordinatesMode = this.coordinatesMode;
  69438. return newTexture;
  69439. };
  69440. ProceduralTexture.prototype.dispose = function () {
  69441. var scene = this.getScene();
  69442. if (!scene) {
  69443. return;
  69444. }
  69445. var index = scene.proceduralTextures.indexOf(this);
  69446. if (index >= 0) {
  69447. scene.proceduralTextures.splice(index, 1);
  69448. }
  69449. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69450. if (vertexBuffer) {
  69451. vertexBuffer.dispose();
  69452. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69453. }
  69454. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69455. this._indexBuffer = null;
  69456. }
  69457. _super.prototype.dispose.call(this);
  69458. };
  69459. __decorate([
  69460. BABYLON.serialize()
  69461. ], ProceduralTexture.prototype, "_size", void 0);
  69462. __decorate([
  69463. BABYLON.serialize()
  69464. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  69465. __decorate([
  69466. BABYLON.serialize()
  69467. ], ProceduralTexture.prototype, "isEnabled", void 0);
  69468. __decorate([
  69469. BABYLON.serialize()
  69470. ], ProceduralTexture.prototype, "refreshRate", null);
  69471. return ProceduralTexture;
  69472. }(BABYLON.Texture));
  69473. BABYLON.ProceduralTexture = ProceduralTexture;
  69474. })(BABYLON || (BABYLON = {}));
  69475. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69476. var BABYLON;
  69477. (function (BABYLON) {
  69478. var CustomProceduralTexture = /** @class */ (function (_super) {
  69479. __extends(CustomProceduralTexture, _super);
  69480. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69481. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69482. _this._animate = true;
  69483. _this._time = 0;
  69484. _this._texturePath = texturePath;
  69485. //Try to load json
  69486. _this.loadJson(texturePath);
  69487. _this.refreshRate = 1;
  69488. return _this;
  69489. }
  69490. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69491. var _this = this;
  69492. var noConfigFile = function () {
  69493. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69494. try {
  69495. _this.setFragment(_this._texturePath);
  69496. }
  69497. catch (ex) {
  69498. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69499. }
  69500. };
  69501. var configFileUrl = jsonUrl + "/config.json";
  69502. var xhr = new XMLHttpRequest();
  69503. xhr.open("GET", configFileUrl, true);
  69504. xhr.addEventListener("load", function () {
  69505. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69506. try {
  69507. _this._config = JSON.parse(xhr.response);
  69508. _this.updateShaderUniforms();
  69509. _this.updateTextures();
  69510. _this.setFragment(_this._texturePath + "/custom");
  69511. _this._animate = _this._config.animate;
  69512. _this.refreshRate = _this._config.refreshrate;
  69513. }
  69514. catch (ex) {
  69515. noConfigFile();
  69516. }
  69517. }
  69518. else {
  69519. noConfigFile();
  69520. }
  69521. }, false);
  69522. xhr.addEventListener("error", function () {
  69523. noConfigFile();
  69524. }, false);
  69525. try {
  69526. xhr.send();
  69527. }
  69528. catch (ex) {
  69529. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69530. }
  69531. };
  69532. CustomProceduralTexture.prototype.isReady = function () {
  69533. if (!_super.prototype.isReady.call(this)) {
  69534. return false;
  69535. }
  69536. for (var name in this._textures) {
  69537. var texture = this._textures[name];
  69538. if (!texture.isReady()) {
  69539. return false;
  69540. }
  69541. }
  69542. return true;
  69543. };
  69544. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69545. var scene = this.getScene();
  69546. if (this._animate && scene) {
  69547. this._time += scene.getAnimationRatio() * 0.03;
  69548. this.updateShaderUniforms();
  69549. }
  69550. _super.prototype.render.call(this, useCameraPostProcess);
  69551. };
  69552. CustomProceduralTexture.prototype.updateTextures = function () {
  69553. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69554. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69555. }
  69556. };
  69557. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69558. if (this._config) {
  69559. for (var j = 0; j < this._config.uniforms.length; j++) {
  69560. var uniform = this._config.uniforms[j];
  69561. switch (uniform.type) {
  69562. case "float":
  69563. this.setFloat(uniform.name, uniform.value);
  69564. break;
  69565. case "color3":
  69566. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69567. break;
  69568. case "color4":
  69569. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69570. break;
  69571. case "vector2":
  69572. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69573. break;
  69574. case "vector3":
  69575. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69576. break;
  69577. }
  69578. }
  69579. }
  69580. this.setFloat("time", this._time);
  69581. };
  69582. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69583. get: function () {
  69584. return this._animate;
  69585. },
  69586. set: function (value) {
  69587. this._animate = value;
  69588. },
  69589. enumerable: true,
  69590. configurable: true
  69591. });
  69592. return CustomProceduralTexture;
  69593. }(BABYLON.ProceduralTexture));
  69594. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69595. })(BABYLON || (BABYLON = {}));
  69596. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69597. var BABYLON;
  69598. (function (BABYLON) {
  69599. var FreeCameraGamepadInput = /** @class */ (function () {
  69600. function FreeCameraGamepadInput() {
  69601. this.gamepadAngularSensibility = 200;
  69602. this.gamepadMoveSensibility = 40;
  69603. // private members
  69604. this._cameraTransform = BABYLON.Matrix.Identity();
  69605. this._deltaTransform = BABYLON.Vector3.Zero();
  69606. this._vector3 = BABYLON.Vector3.Zero();
  69607. this._vector2 = BABYLON.Vector2.Zero();
  69608. }
  69609. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69610. var _this = this;
  69611. var manager = this.camera.getScene().gamepadManager;
  69612. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69613. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69614. // prioritize XBOX gamepads.
  69615. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69616. _this.gamepad = gamepad;
  69617. }
  69618. }
  69619. });
  69620. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69621. if (_this.gamepad === gamepad) {
  69622. _this.gamepad = null;
  69623. }
  69624. });
  69625. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69626. };
  69627. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69628. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69629. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69630. this.gamepad = null;
  69631. };
  69632. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69633. if (this.gamepad && this.gamepad.leftStick) {
  69634. var camera = this.camera;
  69635. var LSValues = this.gamepad.leftStick;
  69636. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69637. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69638. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69639. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69640. var RSValues = this.gamepad.rightStick;
  69641. if (RSValues) {
  69642. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69643. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69644. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69645. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69646. }
  69647. else {
  69648. RSValues = { x: 0, y: 0 };
  69649. }
  69650. if (!camera.rotationQuaternion) {
  69651. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69652. }
  69653. else {
  69654. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69655. }
  69656. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69657. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69658. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69659. camera.cameraDirection.addInPlace(this._deltaTransform);
  69660. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69661. camera.cameraRotation.addInPlace(this._vector2);
  69662. }
  69663. };
  69664. FreeCameraGamepadInput.prototype.getClassName = function () {
  69665. return "FreeCameraGamepadInput";
  69666. };
  69667. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69668. return "gamepad";
  69669. };
  69670. __decorate([
  69671. BABYLON.serialize()
  69672. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69673. __decorate([
  69674. BABYLON.serialize()
  69675. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69676. return FreeCameraGamepadInput;
  69677. }());
  69678. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69679. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69680. })(BABYLON || (BABYLON = {}));
  69681. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69682. var BABYLON;
  69683. (function (BABYLON) {
  69684. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69685. function ArcRotateCameraGamepadInput() {
  69686. this.gamepadRotationSensibility = 80;
  69687. this.gamepadMoveSensibility = 40;
  69688. }
  69689. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69690. var _this = this;
  69691. var manager = this.camera.getScene().gamepadManager;
  69692. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69693. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69694. // prioritize XBOX gamepads.
  69695. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69696. _this.gamepad = gamepad;
  69697. }
  69698. }
  69699. });
  69700. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69701. if (_this.gamepad === gamepad) {
  69702. _this.gamepad = null;
  69703. }
  69704. });
  69705. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69706. };
  69707. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69708. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69709. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69710. this.gamepad = null;
  69711. };
  69712. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69713. if (this.gamepad) {
  69714. var camera = this.camera;
  69715. var RSValues = this.gamepad.rightStick;
  69716. if (RSValues) {
  69717. if (RSValues.x != 0) {
  69718. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69719. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69720. camera.inertialAlphaOffset += normalizedRX;
  69721. }
  69722. }
  69723. if (RSValues.y != 0) {
  69724. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69725. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69726. camera.inertialBetaOffset += normalizedRY;
  69727. }
  69728. }
  69729. }
  69730. var LSValues = this.gamepad.leftStick;
  69731. if (LSValues && LSValues.y != 0) {
  69732. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69733. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69734. this.camera.inertialRadiusOffset -= normalizedLY;
  69735. }
  69736. }
  69737. }
  69738. };
  69739. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69740. return "ArcRotateCameraGamepadInput";
  69741. };
  69742. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69743. return "gamepad";
  69744. };
  69745. __decorate([
  69746. BABYLON.serialize()
  69747. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  69748. __decorate([
  69749. BABYLON.serialize()
  69750. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69751. return ArcRotateCameraGamepadInput;
  69752. }());
  69753. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  69754. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  69755. })(BABYLON || (BABYLON = {}));
  69756. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  69757. var BABYLON;
  69758. (function (BABYLON) {
  69759. var GamepadManager = /** @class */ (function () {
  69760. function GamepadManager(_scene) {
  69761. var _this = this;
  69762. this._scene = _scene;
  69763. this._babylonGamepads = [];
  69764. this._oneGamepadConnected = false;
  69765. this._isMonitoring = false;
  69766. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  69767. if (!BABYLON.Tools.IsWindowObjectExist()) {
  69768. this._gamepadEventSupported = false;
  69769. }
  69770. else {
  69771. this._gamepadEventSupported = 'GamepadEvent' in window;
  69772. this._gamepadSupport = (navigator.getGamepads ||
  69773. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  69774. }
  69775. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  69776. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  69777. for (var i in _this._babylonGamepads) {
  69778. var gamepad = _this._babylonGamepads[i];
  69779. if (gamepad && gamepad._isConnected) {
  69780. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  69781. }
  69782. }
  69783. });
  69784. this._onGamepadConnectedEvent = function (evt) {
  69785. var gamepad = evt.gamepad;
  69786. if (gamepad.index in _this._babylonGamepads) {
  69787. if (_this._babylonGamepads[gamepad.index].isConnected) {
  69788. return;
  69789. }
  69790. }
  69791. var newGamepad;
  69792. if (_this._babylonGamepads[gamepad.index]) {
  69793. newGamepad = _this._babylonGamepads[gamepad.index];
  69794. newGamepad.browserGamepad = gamepad;
  69795. newGamepad._isConnected = true;
  69796. }
  69797. else {
  69798. newGamepad = _this._addNewGamepad(gamepad);
  69799. }
  69800. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69801. _this._startMonitoringGamepads();
  69802. };
  69803. this._onGamepadDisconnectedEvent = function (evt) {
  69804. var gamepad = evt.gamepad;
  69805. // Remove the gamepad from the list of gamepads to monitor.
  69806. for (var i in _this._babylonGamepads) {
  69807. if (_this._babylonGamepads[i].index === gamepad.index) {
  69808. var disconnectedGamepad = _this._babylonGamepads[i];
  69809. disconnectedGamepad._isConnected = false;
  69810. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  69811. break;
  69812. }
  69813. }
  69814. };
  69815. if (this._gamepadSupport) {
  69816. //first add already-connected gamepads
  69817. this._updateGamepadObjects();
  69818. if (this._babylonGamepads.length) {
  69819. this._startMonitoringGamepads();
  69820. }
  69821. // Checking if the gamepad connected event is supported (like in Firefox)
  69822. if (this._gamepadEventSupported) {
  69823. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  69824. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  69825. }
  69826. else {
  69827. this._startMonitoringGamepads();
  69828. }
  69829. }
  69830. }
  69831. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69832. get: function () {
  69833. return this._babylonGamepads;
  69834. },
  69835. enumerable: true,
  69836. configurable: true
  69837. });
  69838. GamepadManager.prototype.getGamepadByType = function (type) {
  69839. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69840. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69841. var gamepad = _a[_i];
  69842. if (gamepad && gamepad.type === type) {
  69843. return gamepad;
  69844. }
  69845. }
  69846. return null;
  69847. };
  69848. GamepadManager.prototype.dispose = function () {
  69849. if (this._gamepadEventSupported) {
  69850. if (this._onGamepadConnectedEvent) {
  69851. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69852. }
  69853. if (this._onGamepadDisconnectedEvent) {
  69854. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69855. }
  69856. this._onGamepadConnectedEvent = null;
  69857. this._onGamepadDisconnectedEvent = null;
  69858. }
  69859. this._babylonGamepads.forEach(function (gamepad) {
  69860. gamepad.dispose();
  69861. });
  69862. this.onGamepadConnectedObservable.clear();
  69863. this.onGamepadDisconnectedObservable.clear();
  69864. this._oneGamepadConnected = false;
  69865. this._stopMonitoringGamepads();
  69866. this._babylonGamepads = [];
  69867. };
  69868. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69869. if (!this._oneGamepadConnected) {
  69870. this._oneGamepadConnected = true;
  69871. }
  69872. var newGamepad;
  69873. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69874. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69875. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69876. }
  69877. // if pose is supported, use the (WebVR) pose enabled controller
  69878. else if (gamepad.pose) {
  69879. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69880. }
  69881. else {
  69882. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69883. }
  69884. this._babylonGamepads[newGamepad.index] = newGamepad;
  69885. return newGamepad;
  69886. };
  69887. GamepadManager.prototype._startMonitoringGamepads = function () {
  69888. if (!this._isMonitoring) {
  69889. this._isMonitoring = true;
  69890. //back-comp
  69891. if (!this._scene) {
  69892. this._checkGamepadsStatus();
  69893. }
  69894. }
  69895. };
  69896. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69897. this._isMonitoring = false;
  69898. };
  69899. GamepadManager.prototype._checkGamepadsStatus = function () {
  69900. var _this = this;
  69901. // Hack to be compatible Chrome
  69902. this._updateGamepadObjects();
  69903. for (var i in this._babylonGamepads) {
  69904. var gamepad = this._babylonGamepads[i];
  69905. if (!gamepad || !gamepad.isConnected) {
  69906. continue;
  69907. }
  69908. gamepad.update();
  69909. }
  69910. if (this._isMonitoring && !this._scene) {
  69911. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69912. }
  69913. };
  69914. // This function is called only on Chrome, which does not properly support
  69915. // connection/disconnection events and forces you to recopy again the gamepad object
  69916. GamepadManager.prototype._updateGamepadObjects = function () {
  69917. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69918. for (var i = 0; i < gamepads.length; i++) {
  69919. var gamepad = gamepads[i];
  69920. if (gamepad) {
  69921. if (!this._babylonGamepads[gamepad.index]) {
  69922. var newGamepad = this._addNewGamepad(gamepad);
  69923. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69924. }
  69925. else {
  69926. // Forced to copy again this object for Chrome for unknown reason
  69927. this._babylonGamepads[i].browserGamepad = gamepad;
  69928. if (!this._babylonGamepads[i].isConnected) {
  69929. this._babylonGamepads[i]._isConnected = true;
  69930. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  69931. }
  69932. }
  69933. }
  69934. }
  69935. };
  69936. return GamepadManager;
  69937. }());
  69938. BABYLON.GamepadManager = GamepadManager;
  69939. })(BABYLON || (BABYLON = {}));
  69940. //# sourceMappingURL=babylon.gamepadManager.js.map
  69941. var BABYLON;
  69942. (function (BABYLON) {
  69943. var StickValues = /** @class */ (function () {
  69944. function StickValues(x, y) {
  69945. this.x = x;
  69946. this.y = y;
  69947. }
  69948. return StickValues;
  69949. }());
  69950. BABYLON.StickValues = StickValues;
  69951. var Gamepad = /** @class */ (function () {
  69952. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  69953. if (leftStickX === void 0) { leftStickX = 0; }
  69954. if (leftStickY === void 0) { leftStickY = 1; }
  69955. if (rightStickX === void 0) { rightStickX = 2; }
  69956. if (rightStickY === void 0) { rightStickY = 3; }
  69957. this.id = id;
  69958. this.index = index;
  69959. this.browserGamepad = browserGamepad;
  69960. this._isConnected = true;
  69961. this._invertLeftStickY = false;
  69962. this.type = Gamepad.GAMEPAD;
  69963. this._leftStickAxisX = leftStickX;
  69964. this._leftStickAxisY = leftStickY;
  69965. this._rightStickAxisX = rightStickX;
  69966. this._rightStickAxisY = rightStickY;
  69967. if (this.browserGamepad.axes.length >= 2) {
  69968. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69969. }
  69970. if (this.browserGamepad.axes.length >= 4) {
  69971. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69972. }
  69973. }
  69974. Object.defineProperty(Gamepad.prototype, "isConnected", {
  69975. get: function () {
  69976. return this._isConnected;
  69977. },
  69978. enumerable: true,
  69979. configurable: true
  69980. });
  69981. Gamepad.prototype.onleftstickchanged = function (callback) {
  69982. this._onleftstickchanged = callback;
  69983. };
  69984. Gamepad.prototype.onrightstickchanged = function (callback) {
  69985. this._onrightstickchanged = callback;
  69986. };
  69987. Object.defineProperty(Gamepad.prototype, "leftStick", {
  69988. get: function () {
  69989. return this._leftStick;
  69990. },
  69991. set: function (newValues) {
  69992. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  69993. this._onleftstickchanged(newValues);
  69994. }
  69995. this._leftStick = newValues;
  69996. },
  69997. enumerable: true,
  69998. configurable: true
  69999. });
  70000. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70001. get: function () {
  70002. return this._rightStick;
  70003. },
  70004. set: function (newValues) {
  70005. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70006. this._onrightstickchanged(newValues);
  70007. }
  70008. this._rightStick = newValues;
  70009. },
  70010. enumerable: true,
  70011. configurable: true
  70012. });
  70013. Gamepad.prototype.update = function () {
  70014. if (this._leftStick) {
  70015. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70016. if (this._invertLeftStickY) {
  70017. this.leftStick.y *= -1;
  70018. }
  70019. }
  70020. if (this._rightStick) {
  70021. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70022. }
  70023. };
  70024. Gamepad.prototype.dispose = function () {
  70025. };
  70026. Gamepad.GAMEPAD = 0;
  70027. Gamepad.GENERIC = 1;
  70028. Gamepad.XBOX = 2;
  70029. Gamepad.POSE_ENABLED = 3;
  70030. return Gamepad;
  70031. }());
  70032. BABYLON.Gamepad = Gamepad;
  70033. var GenericPad = /** @class */ (function (_super) {
  70034. __extends(GenericPad, _super);
  70035. function GenericPad(id, index, browserGamepad) {
  70036. var _this = _super.call(this, id, index, browserGamepad) || this;
  70037. _this.onButtonDownObservable = new BABYLON.Observable();
  70038. _this.onButtonUpObservable = new BABYLON.Observable();
  70039. _this.type = Gamepad.GENERIC;
  70040. _this._buttons = new Array(browserGamepad.buttons.length);
  70041. return _this;
  70042. }
  70043. GenericPad.prototype.onbuttondown = function (callback) {
  70044. this._onbuttondown = callback;
  70045. };
  70046. GenericPad.prototype.onbuttonup = function (callback) {
  70047. this._onbuttonup = callback;
  70048. };
  70049. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70050. if (newValue !== currentValue) {
  70051. if (newValue === 1) {
  70052. if (this._onbuttondown) {
  70053. this._onbuttondown(buttonIndex);
  70054. }
  70055. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70056. }
  70057. if (newValue === 0) {
  70058. if (this._onbuttonup) {
  70059. this._onbuttonup(buttonIndex);
  70060. }
  70061. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70062. }
  70063. }
  70064. return newValue;
  70065. };
  70066. GenericPad.prototype.update = function () {
  70067. _super.prototype.update.call(this);
  70068. for (var index = 0; index < this._buttons.length; index++) {
  70069. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70070. }
  70071. };
  70072. GenericPad.prototype.dispose = function () {
  70073. _super.prototype.dispose.call(this);
  70074. this.onButtonDownObservable.clear();
  70075. this.onButtonUpObservable.clear();
  70076. };
  70077. return GenericPad;
  70078. }(Gamepad));
  70079. BABYLON.GenericPad = GenericPad;
  70080. })(BABYLON || (BABYLON = {}));
  70081. //# sourceMappingURL=babylon.gamepad.js.map
  70082. var BABYLON;
  70083. (function (BABYLON) {
  70084. /**
  70085. * Defines supported buttons for XBox360 compatible gamepads
  70086. */
  70087. var Xbox360Button;
  70088. (function (Xbox360Button) {
  70089. /** A */
  70090. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70091. /** B */
  70092. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70093. /** X */
  70094. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70095. /** Y */
  70096. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70097. /** Start */
  70098. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70099. /** Back */
  70100. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70101. /** Left button */
  70102. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70103. /** Right button */
  70104. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70105. /** Left stick */
  70106. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70107. /** Right stick */
  70108. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70109. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70110. /** Defines values for XBox360 DPad */
  70111. var Xbox360Dpad;
  70112. (function (Xbox360Dpad) {
  70113. /** Up */
  70114. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70115. /** Down */
  70116. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70117. /** Left */
  70118. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70119. /** Right */
  70120. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70121. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70122. /**
  70123. * Defines a XBox360 gamepad
  70124. */
  70125. var Xbox360Pad = /** @class */ (function (_super) {
  70126. __extends(Xbox360Pad, _super);
  70127. /**
  70128. * Creates a new XBox360 gamepad object
  70129. * @param id defines the id of this gamepad
  70130. * @param index defines its index
  70131. * @param gamepad defines the internal HTML gamepad object
  70132. * @param xboxOne defines if it is a XBox One gamepad
  70133. */
  70134. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70135. if (xboxOne === void 0) { xboxOne = false; }
  70136. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70137. _this._leftTrigger = 0;
  70138. _this._rightTrigger = 0;
  70139. /** Observable raised when a button is pressed */
  70140. _this.onButtonDownObservable = new BABYLON.Observable();
  70141. /** Observable raised when a button is released */
  70142. _this.onButtonUpObservable = new BABYLON.Observable();
  70143. /** Observable raised when a pad is pressed */
  70144. _this.onPadDownObservable = new BABYLON.Observable();
  70145. /** Observable raised when a pad is released */
  70146. _this.onPadUpObservable = new BABYLON.Observable();
  70147. _this._buttonA = 0;
  70148. _this._buttonB = 0;
  70149. _this._buttonX = 0;
  70150. _this._buttonY = 0;
  70151. _this._buttonBack = 0;
  70152. _this._buttonStart = 0;
  70153. _this._buttonLB = 0;
  70154. _this._buttonRB = 0;
  70155. _this._buttonLeftStick = 0;
  70156. _this._buttonRightStick = 0;
  70157. _this._dPadUp = 0;
  70158. _this._dPadDown = 0;
  70159. _this._dPadLeft = 0;
  70160. _this._dPadRight = 0;
  70161. _this._isXboxOnePad = false;
  70162. _this.type = BABYLON.Gamepad.XBOX;
  70163. _this._isXboxOnePad = xboxOne;
  70164. return _this;
  70165. }
  70166. /**
  70167. * Defines the callback to call when left trigger is pressed
  70168. * @param callback defines the callback to use
  70169. */
  70170. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70171. this._onlefttriggerchanged = callback;
  70172. };
  70173. /**
  70174. * Defines the callback to call when right trigger is pressed
  70175. * @param callback defines the callback to use
  70176. */
  70177. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70178. this._onrighttriggerchanged = callback;
  70179. };
  70180. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70181. /**
  70182. * Gets or sets left trigger value
  70183. */
  70184. get: function () {
  70185. return this._leftTrigger;
  70186. },
  70187. set: function (newValue) {
  70188. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70189. this._onlefttriggerchanged(newValue);
  70190. }
  70191. this._leftTrigger = newValue;
  70192. },
  70193. enumerable: true,
  70194. configurable: true
  70195. });
  70196. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70197. /**
  70198. * Gets or sets right trigger value
  70199. */
  70200. get: function () {
  70201. return this._rightTrigger;
  70202. },
  70203. set: function (newValue) {
  70204. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70205. this._onrighttriggerchanged(newValue);
  70206. }
  70207. this._rightTrigger = newValue;
  70208. },
  70209. enumerable: true,
  70210. configurable: true
  70211. });
  70212. /**
  70213. * Defines the callback to call when a button is pressed
  70214. * @param callback defines the callback to use
  70215. */
  70216. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70217. this._onbuttondown = callback;
  70218. };
  70219. /**
  70220. * Defines the callback to call when a button is released
  70221. * @param callback defines the callback to use
  70222. */
  70223. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70224. this._onbuttonup = callback;
  70225. };
  70226. /**
  70227. * Defines the callback to call when a pad is pressed
  70228. * @param callback defines the callback to use
  70229. */
  70230. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70231. this._ondpaddown = callback;
  70232. };
  70233. /**
  70234. * Defines the callback to call when a pad is released
  70235. * @param callback defines the callback to use
  70236. */
  70237. Xbox360Pad.prototype.ondpadup = function (callback) {
  70238. this._ondpadup = callback;
  70239. };
  70240. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70241. if (newValue !== currentValue) {
  70242. if (newValue === 1) {
  70243. if (this._onbuttondown) {
  70244. this._onbuttondown(buttonType);
  70245. }
  70246. this.onButtonDownObservable.notifyObservers(buttonType);
  70247. }
  70248. if (newValue === 0) {
  70249. if (this._onbuttonup) {
  70250. this._onbuttonup(buttonType);
  70251. }
  70252. this.onButtonUpObservable.notifyObservers(buttonType);
  70253. }
  70254. }
  70255. return newValue;
  70256. };
  70257. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70258. if (newValue !== currentValue) {
  70259. if (newValue === 1) {
  70260. if (this._ondpaddown) {
  70261. this._ondpaddown(buttonType);
  70262. }
  70263. this.onPadDownObservable.notifyObservers(buttonType);
  70264. }
  70265. if (newValue === 0) {
  70266. if (this._ondpadup) {
  70267. this._ondpadup(buttonType);
  70268. }
  70269. this.onPadUpObservable.notifyObservers(buttonType);
  70270. }
  70271. }
  70272. return newValue;
  70273. };
  70274. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70275. /** Gets or sets value of A button */
  70276. get: function () {
  70277. return this._buttonA;
  70278. },
  70279. set: function (value) {
  70280. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70281. },
  70282. enumerable: true,
  70283. configurable: true
  70284. });
  70285. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70286. /** Gets or sets value of B button */
  70287. get: function () {
  70288. return this._buttonB;
  70289. },
  70290. set: function (value) {
  70291. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70292. },
  70293. enumerable: true,
  70294. configurable: true
  70295. });
  70296. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70297. /** Gets or sets value of X button */
  70298. get: function () {
  70299. return this._buttonX;
  70300. },
  70301. set: function (value) {
  70302. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70303. },
  70304. enumerable: true,
  70305. configurable: true
  70306. });
  70307. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70308. /** Gets or sets value of Y button */
  70309. get: function () {
  70310. return this._buttonY;
  70311. },
  70312. set: function (value) {
  70313. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70314. },
  70315. enumerable: true,
  70316. configurable: true
  70317. });
  70318. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70319. /** Gets or sets value of Start button */
  70320. get: function () {
  70321. return this._buttonStart;
  70322. },
  70323. set: function (value) {
  70324. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70325. },
  70326. enumerable: true,
  70327. configurable: true
  70328. });
  70329. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70330. /** Gets or sets value of Back button */
  70331. get: function () {
  70332. return this._buttonBack;
  70333. },
  70334. set: function (value) {
  70335. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70336. },
  70337. enumerable: true,
  70338. configurable: true
  70339. });
  70340. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70341. /** Gets or sets value of Left button */
  70342. get: function () {
  70343. return this._buttonLB;
  70344. },
  70345. set: function (value) {
  70346. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70347. },
  70348. enumerable: true,
  70349. configurable: true
  70350. });
  70351. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70352. /** Gets or sets value of Right button */
  70353. get: function () {
  70354. return this._buttonRB;
  70355. },
  70356. set: function (value) {
  70357. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70358. },
  70359. enumerable: true,
  70360. configurable: true
  70361. });
  70362. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70363. /** Gets or sets value of left stick */
  70364. get: function () {
  70365. return this._buttonLeftStick;
  70366. },
  70367. set: function (value) {
  70368. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70369. },
  70370. enumerable: true,
  70371. configurable: true
  70372. });
  70373. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70374. /** Gets or sets value of right stick */
  70375. get: function () {
  70376. return this._buttonRightStick;
  70377. },
  70378. set: function (value) {
  70379. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70380. },
  70381. enumerable: true,
  70382. configurable: true
  70383. });
  70384. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70385. /** Gets or sets value of DPad up */
  70386. get: function () {
  70387. return this._dPadUp;
  70388. },
  70389. set: function (value) {
  70390. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70391. },
  70392. enumerable: true,
  70393. configurable: true
  70394. });
  70395. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70396. /** Gets or sets value of DPad down */
  70397. get: function () {
  70398. return this._dPadDown;
  70399. },
  70400. set: function (value) {
  70401. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70402. },
  70403. enumerable: true,
  70404. configurable: true
  70405. });
  70406. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70407. /** Gets or sets value of DPad left */
  70408. get: function () {
  70409. return this._dPadLeft;
  70410. },
  70411. set: function (value) {
  70412. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70413. },
  70414. enumerable: true,
  70415. configurable: true
  70416. });
  70417. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70418. /** Gets or sets value of DPad right */
  70419. get: function () {
  70420. return this._dPadRight;
  70421. },
  70422. set: function (value) {
  70423. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70424. },
  70425. enumerable: true,
  70426. configurable: true
  70427. });
  70428. /**
  70429. * Force the gamepad to synchronize with device values
  70430. */
  70431. Xbox360Pad.prototype.update = function () {
  70432. _super.prototype.update.call(this);
  70433. if (this._isXboxOnePad) {
  70434. this.buttonA = this.browserGamepad.buttons[0].value;
  70435. this.buttonB = this.browserGamepad.buttons[1].value;
  70436. this.buttonX = this.browserGamepad.buttons[2].value;
  70437. this.buttonY = this.browserGamepad.buttons[3].value;
  70438. this.buttonLB = this.browserGamepad.buttons[4].value;
  70439. this.buttonRB = this.browserGamepad.buttons[5].value;
  70440. this.leftTrigger = this.browserGamepad.axes[2];
  70441. this.rightTrigger = this.browserGamepad.axes[5];
  70442. this.buttonBack = this.browserGamepad.buttons[9].value;
  70443. this.buttonStart = this.browserGamepad.buttons[8].value;
  70444. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70445. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70446. this.dPadUp = this.browserGamepad.buttons[11].value;
  70447. this.dPadDown = this.browserGamepad.buttons[12].value;
  70448. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70449. this.dPadRight = this.browserGamepad.buttons[14].value;
  70450. }
  70451. else {
  70452. this.buttonA = this.browserGamepad.buttons[0].value;
  70453. this.buttonB = this.browserGamepad.buttons[1].value;
  70454. this.buttonX = this.browserGamepad.buttons[2].value;
  70455. this.buttonY = this.browserGamepad.buttons[3].value;
  70456. this.buttonLB = this.browserGamepad.buttons[4].value;
  70457. this.buttonRB = this.browserGamepad.buttons[5].value;
  70458. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70459. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70460. this.buttonBack = this.browserGamepad.buttons[8].value;
  70461. this.buttonStart = this.browserGamepad.buttons[9].value;
  70462. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70463. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70464. this.dPadUp = this.browserGamepad.buttons[12].value;
  70465. this.dPadDown = this.browserGamepad.buttons[13].value;
  70466. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70467. this.dPadRight = this.browserGamepad.buttons[15].value;
  70468. }
  70469. };
  70470. Xbox360Pad.prototype.dispose = function () {
  70471. _super.prototype.dispose.call(this);
  70472. this.onButtonDownObservable.clear();
  70473. this.onButtonUpObservable.clear();
  70474. this.onPadDownObservable.clear();
  70475. this.onPadUpObservable.clear();
  70476. };
  70477. return Xbox360Pad;
  70478. }(BABYLON.Gamepad));
  70479. BABYLON.Xbox360Pad = Xbox360Pad;
  70480. })(BABYLON || (BABYLON = {}));
  70481. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70482. var BABYLON;
  70483. (function (BABYLON) {
  70484. /**
  70485. * Defines the types of pose enabled controllers that are supported
  70486. */
  70487. var PoseEnabledControllerType;
  70488. (function (PoseEnabledControllerType) {
  70489. /**
  70490. * HTC Vive
  70491. */
  70492. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70493. /**
  70494. * Oculus Rift
  70495. */
  70496. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70497. /**
  70498. * Windows mixed reality
  70499. */
  70500. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70501. /**
  70502. * Samsung gear VR
  70503. */
  70504. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70505. /**
  70506. * Google Daydream
  70507. */
  70508. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70509. /**
  70510. * Generic
  70511. */
  70512. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70513. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70514. /**
  70515. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70516. */
  70517. var PoseEnabledControllerHelper = /** @class */ (function () {
  70518. function PoseEnabledControllerHelper() {
  70519. }
  70520. /**
  70521. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70522. * @param vrGamepad the gamepad to initialized
  70523. * @returns a vr controller of the type the gamepad identified as
  70524. */
  70525. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70526. // Oculus Touch
  70527. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70528. return new BABYLON.OculusTouchController(vrGamepad);
  70529. }
  70530. // Windows Mixed Reality controllers
  70531. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70532. return new BABYLON.WindowsMotionController(vrGamepad);
  70533. }
  70534. // HTC Vive
  70535. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70536. return new BABYLON.ViveController(vrGamepad);
  70537. }
  70538. // Samsung/Oculus Gear VR or Oculus Go
  70539. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  70540. return new BABYLON.GearVRController(vrGamepad);
  70541. }
  70542. // Google Daydream
  70543. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70544. return new BABYLON.DaydreamController(vrGamepad);
  70545. }
  70546. // Generic
  70547. else {
  70548. return new BABYLON.GenericController(vrGamepad);
  70549. }
  70550. };
  70551. return PoseEnabledControllerHelper;
  70552. }());
  70553. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70554. /**
  70555. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70556. */
  70557. var PoseEnabledController = /** @class */ (function (_super) {
  70558. __extends(PoseEnabledController, _super);
  70559. /**
  70560. * Creates a new PoseEnabledController from a gamepad
  70561. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70562. */
  70563. function PoseEnabledController(browserGamepad) {
  70564. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70565. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70566. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70567. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70568. /**
  70569. * The device position in babylon space
  70570. */
  70571. _this.devicePosition = BABYLON.Vector3.Zero();
  70572. /**
  70573. * The device rotation in babylon space
  70574. */
  70575. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70576. /**
  70577. * The scale factor of the device in babylon space
  70578. */
  70579. _this.deviceScaleFactor = 1;
  70580. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70581. /**
  70582. * Internal, matrix used to convert room space to babylon space
  70583. */
  70584. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70585. /**
  70586. * Node to be used when casting a ray from the controller
  70587. */
  70588. _this._pointingPoseNode = null;
  70589. _this._workingMatrix = BABYLON.Matrix.Identity();
  70590. /**
  70591. * @hidden
  70592. */
  70593. _this._meshAttachedObservable = new BABYLON.Observable();
  70594. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70595. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70596. _this.position = BABYLON.Vector3.Zero();
  70597. _this.rotationQuaternion = new BABYLON.Quaternion();
  70598. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70599. _this._calculatedRotation = new BABYLON.Quaternion();
  70600. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70601. return _this;
  70602. }
  70603. /**
  70604. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70605. */
  70606. PoseEnabledController.prototype.update = function () {
  70607. _super.prototype.update.call(this);
  70608. var pose = this.browserGamepad.pose;
  70609. this.updateFromDevice(pose);
  70610. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70611. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70612. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70613. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70614. if (this._mesh) {
  70615. this._mesh.position.copyFrom(this.devicePosition);
  70616. if (this._mesh.rotationQuaternion) {
  70617. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70618. }
  70619. }
  70620. };
  70621. /**
  70622. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70623. * @param poseData raw pose fromthe device
  70624. */
  70625. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70626. if (poseData) {
  70627. this.rawPose = poseData;
  70628. if (poseData.position) {
  70629. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70630. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70631. this._deviceRoomPosition.z *= -1;
  70632. }
  70633. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70634. this._calculatedPosition.addInPlace(this.position);
  70635. }
  70636. var pose = this.rawPose;
  70637. if (poseData.orientation && pose.orientation) {
  70638. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70639. if (this._mesh) {
  70640. if (this._mesh.getScene().useRightHandedSystem) {
  70641. this._deviceRoomRotationQuaternion.z *= -1;
  70642. this._deviceRoomRotationQuaternion.w *= -1;
  70643. }
  70644. else {
  70645. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70646. }
  70647. }
  70648. // if the camera is set, rotate to the camera's rotation
  70649. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70650. }
  70651. }
  70652. };
  70653. /**
  70654. * Attaches a mesh to the controller
  70655. * @param mesh the mesh to be attached
  70656. */
  70657. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70658. if (this._mesh) {
  70659. this._mesh.parent = null;
  70660. }
  70661. this._mesh = mesh;
  70662. if (this._poseControlledCamera) {
  70663. this._mesh.parent = this._poseControlledCamera;
  70664. }
  70665. if (!this._mesh.rotationQuaternion) {
  70666. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70667. }
  70668. this._meshAttachedObservable.notifyObservers(mesh);
  70669. };
  70670. /**
  70671. * Attaches the controllers mesh to a camera
  70672. * @param camera the camera the mesh should be attached to
  70673. */
  70674. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70675. this._poseControlledCamera = camera;
  70676. if (this._mesh) {
  70677. this._mesh.parent = this._poseControlledCamera;
  70678. }
  70679. };
  70680. /**
  70681. * Disposes of the controller
  70682. */
  70683. PoseEnabledController.prototype.dispose = function () {
  70684. if (this._mesh) {
  70685. this._mesh.dispose();
  70686. }
  70687. this._mesh = null;
  70688. _super.prototype.dispose.call(this);
  70689. };
  70690. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70691. /**
  70692. * The mesh that is attached to the controller
  70693. */
  70694. get: function () {
  70695. return this._mesh;
  70696. },
  70697. enumerable: true,
  70698. configurable: true
  70699. });
  70700. /**
  70701. * Gets the ray of the controller in the direction the controller is pointing
  70702. * @param length the length the resulting ray should be
  70703. * @returns a ray in the direction the controller is pointing
  70704. */
  70705. PoseEnabledController.prototype.getForwardRay = function (length) {
  70706. if (length === void 0) { length = 100; }
  70707. if (!this.mesh) {
  70708. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70709. }
  70710. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70711. var origin = m.getTranslation();
  70712. var forward = new BABYLON.Vector3(0, 0, -1);
  70713. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70714. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70715. return new BABYLON.Ray(origin, direction, length);
  70716. };
  70717. /**
  70718. * Name of the child mesh that can be used to cast a ray from the controller
  70719. */
  70720. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70721. return PoseEnabledController;
  70722. }(BABYLON.Gamepad));
  70723. BABYLON.PoseEnabledController = PoseEnabledController;
  70724. })(BABYLON || (BABYLON = {}));
  70725. //# sourceMappingURL=babylon.poseEnabledController.js.map
  70726. var BABYLON;
  70727. (function (BABYLON) {
  70728. /**
  70729. * Defines the WebVRController object that represents controllers tracked in 3D space
  70730. */
  70731. var WebVRController = /** @class */ (function (_super) {
  70732. __extends(WebVRController, _super);
  70733. /**
  70734. * Creates a new WebVRController from a gamepad
  70735. * @param vrGamepad the gamepad that the WebVRController should be created from
  70736. */
  70737. function WebVRController(vrGamepad) {
  70738. var _this = _super.call(this, vrGamepad) || this;
  70739. // Observables
  70740. /**
  70741. * Fired when the trigger state has changed
  70742. */
  70743. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  70744. /**
  70745. * Fired when the main button state has changed
  70746. */
  70747. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  70748. /**
  70749. * Fired when the secondary button state has changed
  70750. */
  70751. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  70752. /**
  70753. * Fired when the pad state has changed
  70754. */
  70755. _this.onPadStateChangedObservable = new BABYLON.Observable();
  70756. /**
  70757. * Fired when controllers stick values have changed
  70758. */
  70759. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  70760. /**
  70761. * X and Y axis corrisponding to the controllers joystick
  70762. */
  70763. _this.pad = { x: 0, y: 0 };
  70764. // avoid GC, store state in a tmp object
  70765. _this._changes = {
  70766. pressChanged: false,
  70767. touchChanged: false,
  70768. valueChanged: false,
  70769. changed: false
  70770. };
  70771. _this._buttons = new Array(vrGamepad.buttons.length);
  70772. _this.hand = vrGamepad.hand;
  70773. return _this;
  70774. }
  70775. /**
  70776. * Fired when a controller button's state has changed
  70777. * @param callback the callback containing the button that was modified
  70778. */
  70779. WebVRController.prototype.onButtonStateChange = function (callback) {
  70780. this._onButtonStateChange = callback;
  70781. };
  70782. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  70783. /**
  70784. * The default controller model for the controller
  70785. */
  70786. get: function () {
  70787. return this._defaultModel;
  70788. },
  70789. enumerable: true,
  70790. configurable: true
  70791. });
  70792. /**
  70793. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  70794. */
  70795. WebVRController.prototype.update = function () {
  70796. _super.prototype.update.call(this);
  70797. for (var index = 0; index < this._buttons.length; index++) {
  70798. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  70799. }
  70800. ;
  70801. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  70802. this.pad.x = this.leftStick.x;
  70803. this.pad.y = this.leftStick.y;
  70804. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  70805. }
  70806. };
  70807. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  70808. if (!newState) {
  70809. newState = {
  70810. pressed: false,
  70811. touched: false,
  70812. value: 0
  70813. };
  70814. }
  70815. if (!currentState) {
  70816. this._buttons[buttonIndex] = {
  70817. pressed: newState.pressed,
  70818. touched: newState.touched,
  70819. value: newState.value
  70820. };
  70821. return;
  70822. }
  70823. this._checkChanges(newState, currentState);
  70824. if (this._changes.changed) {
  70825. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  70826. this._handleButtonChange(buttonIndex, newState, this._changes);
  70827. }
  70828. this._buttons[buttonIndex].pressed = newState.pressed;
  70829. this._buttons[buttonIndex].touched = newState.touched;
  70830. // oculus triggers are never 0, thou not touched.
  70831. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  70832. };
  70833. WebVRController.prototype._checkChanges = function (newState, currentState) {
  70834. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  70835. this._changes.touchChanged = newState.touched !== currentState.touched;
  70836. this._changes.valueChanged = newState.value !== currentState.value;
  70837. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  70838. return this._changes;
  70839. };
  70840. /**
  70841. * Disposes of th webVRCOntroller
  70842. */
  70843. WebVRController.prototype.dispose = function () {
  70844. _super.prototype.dispose.call(this);
  70845. this.onTriggerStateChangedObservable.clear();
  70846. this.onMainButtonStateChangedObservable.clear();
  70847. this.onSecondaryButtonStateChangedObservable.clear();
  70848. this.onPadStateChangedObservable.clear();
  70849. this.onPadValuesChangedObservable.clear();
  70850. };
  70851. return WebVRController;
  70852. }(BABYLON.PoseEnabledController));
  70853. BABYLON.WebVRController = WebVRController;
  70854. })(BABYLON || (BABYLON = {}));
  70855. //# sourceMappingURL=babylon.webVRController.js.map
  70856. var BABYLON;
  70857. (function (BABYLON) {
  70858. /**
  70859. * Oculus Touch Controller
  70860. */
  70861. var OculusTouchController = /** @class */ (function (_super) {
  70862. __extends(OculusTouchController, _super);
  70863. /**
  70864. * Creates a new OculusTouchController from a gamepad
  70865. * @param vrGamepad the gamepad that the controller should be created from
  70866. */
  70867. function OculusTouchController(vrGamepad) {
  70868. var _this = _super.call(this, vrGamepad) || this;
  70869. /**
  70870. * Fired when the secondary trigger on this controller is modified
  70871. */
  70872. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  70873. /**
  70874. * Fired when the thumb rest on this controller is modified
  70875. */
  70876. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  70877. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  70878. return _this;
  70879. }
  70880. /**
  70881. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70882. * @param scene scene in which to add meshes
  70883. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70884. */
  70885. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70886. var _this = this;
  70887. var meshName;
  70888. // Hand
  70889. if (this.hand === 'left') {
  70890. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  70891. }
  70892. else { // Right is the default if no hand is specified
  70893. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  70894. }
  70895. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  70896. /*
  70897. Parent Mesh name: oculus_touch_left
  70898. - body
  70899. - trigger
  70900. - thumbstick
  70901. - grip
  70902. - button_y
  70903. - button_x
  70904. - button_enter
  70905. */
  70906. _this._defaultModel = newMeshes[1];
  70907. _this.attachToMesh(_this._defaultModel);
  70908. if (meshLoaded) {
  70909. meshLoaded(_this._defaultModel);
  70910. }
  70911. });
  70912. };
  70913. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  70914. /**
  70915. * Fired when the A button on this controller is modified
  70916. */
  70917. get: function () {
  70918. if (this.hand === 'right') {
  70919. return this.onMainButtonStateChangedObservable;
  70920. }
  70921. else {
  70922. throw new Error('No A button on left hand');
  70923. }
  70924. },
  70925. enumerable: true,
  70926. configurable: true
  70927. });
  70928. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  70929. /**
  70930. * Fired when the B button on this controller is modified
  70931. */
  70932. get: function () {
  70933. if (this.hand === 'right') {
  70934. return this.onSecondaryButtonStateChangedObservable;
  70935. }
  70936. else {
  70937. throw new Error('No B button on left hand');
  70938. }
  70939. },
  70940. enumerable: true,
  70941. configurable: true
  70942. });
  70943. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  70944. /**
  70945. * Fired when the X button on this controller is modified
  70946. */
  70947. get: function () {
  70948. if (this.hand === 'left') {
  70949. return this.onMainButtonStateChangedObservable;
  70950. }
  70951. else {
  70952. throw new Error('No X button on right hand');
  70953. }
  70954. },
  70955. enumerable: true,
  70956. configurable: true
  70957. });
  70958. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  70959. /**
  70960. * Fired when the Y button on this controller is modified
  70961. */
  70962. get: function () {
  70963. if (this.hand === 'left') {
  70964. return this.onSecondaryButtonStateChangedObservable;
  70965. }
  70966. else {
  70967. throw new Error('No Y button on right hand');
  70968. }
  70969. },
  70970. enumerable: true,
  70971. configurable: true
  70972. });
  70973. /**
  70974. * Called once for each button that changed state since the last frame
  70975. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  70976. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  70977. * 2) secondary trigger (same)
  70978. * 3) A (right) X (left), touch, pressed = value
  70979. * 4) B / Y
  70980. * 5) thumb rest
  70981. * @param buttonIdx Which button index changed
  70982. * @param state New state of the button
  70983. * @param changes Which properties on the state changed since last frame
  70984. */
  70985. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70986. var notifyObject = state; //{ state: state, changes: changes };
  70987. var triggerDirection = this.hand === 'right' ? -1 : 1;
  70988. switch (buttonIdx) {
  70989. case 0:
  70990. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70991. return;
  70992. case 1: // index trigger
  70993. if (this._defaultModel) {
  70994. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  70995. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  70996. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  70997. }
  70998. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70999. return;
  71000. case 2: // secondary trigger
  71001. if (this._defaultModel) {
  71002. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71003. }
  71004. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71005. return;
  71006. case 3:
  71007. if (this._defaultModel) {
  71008. if (notifyObject.pressed) {
  71009. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71010. }
  71011. else {
  71012. (this._defaultModel.getChildren()[1]).position.y = 0;
  71013. }
  71014. }
  71015. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71016. return;
  71017. case 4:
  71018. if (this._defaultModel) {
  71019. if (notifyObject.pressed) {
  71020. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71021. }
  71022. else {
  71023. (this._defaultModel.getChildren()[2]).position.y = 0;
  71024. }
  71025. }
  71026. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71027. return;
  71028. case 5:
  71029. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71030. return;
  71031. }
  71032. };
  71033. /**
  71034. * Base Url for the controller model.
  71035. */
  71036. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71037. /**
  71038. * File name for the left controller model.
  71039. */
  71040. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71041. /**
  71042. * File name for the right controller model.
  71043. */
  71044. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71045. return OculusTouchController;
  71046. }(BABYLON.WebVRController));
  71047. BABYLON.OculusTouchController = OculusTouchController;
  71048. })(BABYLON || (BABYLON = {}));
  71049. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71050. var BABYLON;
  71051. (function (BABYLON) {
  71052. /**
  71053. * Vive Controller
  71054. */
  71055. var ViveController = /** @class */ (function (_super) {
  71056. __extends(ViveController, _super);
  71057. /**
  71058. * Creates a new ViveController from a gamepad
  71059. * @param vrGamepad the gamepad that the controller should be created from
  71060. */
  71061. function ViveController(vrGamepad) {
  71062. var _this = _super.call(this, vrGamepad) || this;
  71063. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71064. _this._invertLeftStickY = true;
  71065. return _this;
  71066. }
  71067. /**
  71068. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71069. * @param scene scene in which to add meshes
  71070. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71071. */
  71072. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71073. var _this = this;
  71074. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71075. /*
  71076. Parent Mesh name: ViveWand
  71077. - body
  71078. - r_gripper
  71079. - l_gripper
  71080. - menu_button
  71081. - system_button
  71082. - trackpad
  71083. - trigger
  71084. - LED
  71085. */
  71086. _this._defaultModel = newMeshes[1];
  71087. _this.attachToMesh(_this._defaultModel);
  71088. if (meshLoaded) {
  71089. meshLoaded(_this._defaultModel);
  71090. }
  71091. });
  71092. };
  71093. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71094. /**
  71095. * Fired when the left button on this controller is modified
  71096. */
  71097. get: function () {
  71098. return this.onMainButtonStateChangedObservable;
  71099. },
  71100. enumerable: true,
  71101. configurable: true
  71102. });
  71103. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71104. /**
  71105. * Fired when the right button on this controller is modified
  71106. */
  71107. get: function () {
  71108. return this.onMainButtonStateChangedObservable;
  71109. },
  71110. enumerable: true,
  71111. configurable: true
  71112. });
  71113. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71114. /**
  71115. * Fired when the menu button on this controller is modified
  71116. */
  71117. get: function () {
  71118. return this.onSecondaryButtonStateChangedObservable;
  71119. },
  71120. enumerable: true,
  71121. configurable: true
  71122. });
  71123. /**
  71124. * Called once for each button that changed state since the last frame
  71125. * Vive mapping:
  71126. * 0: touchpad
  71127. * 1: trigger
  71128. * 2: left AND right buttons
  71129. * 3: menu button
  71130. * @param buttonIdx Which button index changed
  71131. * @param state New state of the button
  71132. * @param changes Which properties on the state changed since last frame
  71133. */
  71134. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71135. var notifyObject = state; //{ state: state, changes: changes };
  71136. switch (buttonIdx) {
  71137. case 0:
  71138. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71139. return;
  71140. case 1: // index trigger
  71141. if (this._defaultModel) {
  71142. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71143. }
  71144. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71145. return;
  71146. case 2: // left AND right button
  71147. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71148. return;
  71149. case 3:
  71150. if (this._defaultModel) {
  71151. if (notifyObject.pressed) {
  71152. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71153. }
  71154. else {
  71155. (this._defaultModel.getChildren()[2]).position.y = 0;
  71156. }
  71157. }
  71158. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71159. return;
  71160. }
  71161. };
  71162. /**
  71163. * Base Url for the controller model.
  71164. */
  71165. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71166. /**
  71167. * File name for the controller model.
  71168. */
  71169. ViveController.MODEL_FILENAME = 'wand.babylon';
  71170. return ViveController;
  71171. }(BABYLON.WebVRController));
  71172. BABYLON.ViveController = ViveController;
  71173. })(BABYLON || (BABYLON = {}));
  71174. //# sourceMappingURL=babylon.viveController.js.map
  71175. var BABYLON;
  71176. (function (BABYLON) {
  71177. /**
  71178. * Generic Controller
  71179. */
  71180. var GenericController = /** @class */ (function (_super) {
  71181. __extends(GenericController, _super);
  71182. /**
  71183. * Creates a new GenericController from a gamepad
  71184. * @param vrGamepad the gamepad that the controller should be created from
  71185. */
  71186. function GenericController(vrGamepad) {
  71187. return _super.call(this, vrGamepad) || this;
  71188. }
  71189. /**
  71190. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71191. * @param scene scene in which to add meshes
  71192. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71193. */
  71194. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71195. var _this = this;
  71196. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71197. _this._defaultModel = newMeshes[1];
  71198. _this.attachToMesh(_this._defaultModel);
  71199. if (meshLoaded) {
  71200. meshLoaded(_this._defaultModel);
  71201. }
  71202. });
  71203. };
  71204. /**
  71205. * Called once for each button that changed state since the last frame
  71206. * @param buttonIdx Which button index changed
  71207. * @param state New state of the button
  71208. * @param changes Which properties on the state changed since last frame
  71209. */
  71210. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71211. console.log("Button id: " + buttonIdx + "state: ");
  71212. console.dir(state);
  71213. };
  71214. /**
  71215. * Base Url for the controller model.
  71216. */
  71217. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71218. /**
  71219. * File name for the controller model.
  71220. */
  71221. GenericController.MODEL_FILENAME = 'generic.babylon';
  71222. return GenericController;
  71223. }(BABYLON.WebVRController));
  71224. BABYLON.GenericController = GenericController;
  71225. })(BABYLON || (BABYLON = {}));
  71226. //# sourceMappingURL=babylon.genericController.js.map
  71227. var BABYLON;
  71228. (function (BABYLON) {
  71229. /**
  71230. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71231. */
  71232. var LoadedMeshInfo = /** @class */ (function () {
  71233. function LoadedMeshInfo() {
  71234. /**
  71235. * Map of the button meshes contained in the controller
  71236. */
  71237. this.buttonMeshes = {};
  71238. /**
  71239. * Map of the axis meshes contained in the controller
  71240. */
  71241. this.axisMeshes = {};
  71242. }
  71243. return LoadedMeshInfo;
  71244. }());
  71245. /**
  71246. * Defines the WindowsMotionController object that the state of the windows motion controller
  71247. */
  71248. var WindowsMotionController = /** @class */ (function (_super) {
  71249. __extends(WindowsMotionController, _super);
  71250. /**
  71251. * Creates a new WindowsMotionController from a gamepad
  71252. * @param vrGamepad the gamepad that the controller should be created from
  71253. */
  71254. function WindowsMotionController(vrGamepad) {
  71255. var _this = _super.call(this, vrGamepad) || this;
  71256. _this._mapping = {
  71257. // Semantic button names
  71258. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71259. // A mapping of the button name to glTF model node name
  71260. // that should be transformed by button value.
  71261. buttonMeshNames: {
  71262. 'trigger': 'SELECT',
  71263. 'menu': 'MENU',
  71264. 'grip': 'GRASP',
  71265. 'thumbstick': 'THUMBSTICK_PRESS',
  71266. 'trackpad': 'TOUCHPAD_PRESS'
  71267. },
  71268. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71269. buttonObservableNames: {
  71270. 'trigger': 'onTriggerStateChangedObservable',
  71271. 'menu': 'onSecondaryButtonStateChangedObservable',
  71272. 'grip': 'onMainButtonStateChangedObservable',
  71273. 'thumbstick': 'onPadStateChangedObservable',
  71274. 'trackpad': 'onTrackpadChangedObservable'
  71275. },
  71276. // A mapping of the axis name to glTF model node name
  71277. // that should be transformed by axis value.
  71278. // This array mirrors the browserGamepad.axes array, such that
  71279. // the mesh corresponding to axis 0 is in this array index 0.
  71280. axisMeshNames: [
  71281. 'THUMBSTICK_X',
  71282. 'THUMBSTICK_Y',
  71283. 'TOUCHPAD_TOUCH_X',
  71284. 'TOUCHPAD_TOUCH_Y'
  71285. ],
  71286. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71287. };
  71288. /**
  71289. * Fired when the trackpad on this controller is clicked
  71290. */
  71291. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71292. /**
  71293. * Fired when the trackpad on this controller is modified
  71294. */
  71295. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71296. /**
  71297. * The current x and y values of this controller's trackpad
  71298. */
  71299. _this.trackpad = { x: 0, y: 0 };
  71300. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71301. _this._loadedMeshInfo = null;
  71302. return _this;
  71303. }
  71304. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71305. /**
  71306. * Fired when the trigger on this controller is modified
  71307. */
  71308. get: function () {
  71309. return this.onTriggerStateChangedObservable;
  71310. },
  71311. enumerable: true,
  71312. configurable: true
  71313. });
  71314. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71315. /**
  71316. * Fired when the menu button on this controller is modified
  71317. */
  71318. get: function () {
  71319. return this.onSecondaryButtonStateChangedObservable;
  71320. },
  71321. enumerable: true,
  71322. configurable: true
  71323. });
  71324. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71325. /**
  71326. * Fired when the grip button on this controller is modified
  71327. */
  71328. get: function () {
  71329. return this.onMainButtonStateChangedObservable;
  71330. },
  71331. enumerable: true,
  71332. configurable: true
  71333. });
  71334. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71335. /**
  71336. * Fired when the thumbstick button on this controller is modified
  71337. */
  71338. get: function () {
  71339. return this.onPadStateChangedObservable;
  71340. },
  71341. enumerable: true,
  71342. configurable: true
  71343. });
  71344. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71345. /**
  71346. * Fired when the touchpad button on this controller is modified
  71347. */
  71348. get: function () {
  71349. return this.onTrackpadChangedObservable;
  71350. },
  71351. enumerable: true,
  71352. configurable: true
  71353. });
  71354. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71355. /**
  71356. * Fired when the touchpad values on this controller are modified
  71357. */
  71358. get: function () {
  71359. return this.onTrackpadValuesChangedObservable;
  71360. },
  71361. enumerable: true,
  71362. configurable: true
  71363. });
  71364. WindowsMotionController.prototype._updateTrackpad = function () {
  71365. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  71366. this.trackpad.x = this.browserGamepad["axes"][2];
  71367. this.trackpad.y = this.browserGamepad["axes"][3];
  71368. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71369. }
  71370. };
  71371. /**
  71372. * Called once per frame by the engine.
  71373. */
  71374. WindowsMotionController.prototype.update = function () {
  71375. _super.prototype.update.call(this);
  71376. if (this.browserGamepad.axes) {
  71377. this._updateTrackpad();
  71378. // Only need to animate axes if there is a loaded mesh
  71379. if (this._loadedMeshInfo) {
  71380. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71381. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71382. }
  71383. }
  71384. }
  71385. };
  71386. /**
  71387. * Called once for each button that changed state since the last frame
  71388. * @param buttonIdx Which button index changed
  71389. * @param state New state of the button
  71390. * @param changes Which properties on the state changed since last frame
  71391. */
  71392. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71393. var buttonName = this._mapping.buttons[buttonIdx];
  71394. if (!buttonName) {
  71395. return;
  71396. }
  71397. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  71398. this._updateTrackpad();
  71399. // Only emit events for buttons that we know how to map from index to name
  71400. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71401. if (observable) {
  71402. observable.notifyObservers(state);
  71403. }
  71404. this._lerpButtonTransform(buttonName, state.value);
  71405. };
  71406. /**
  71407. * Moves the buttons on the controller mesh based on their current state
  71408. * @param buttonName the name of the button to move
  71409. * @param buttonValue the value of the button which determines the buttons new position
  71410. */
  71411. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71412. // If there is no loaded mesh, there is nothing to transform.
  71413. if (!this._loadedMeshInfo) {
  71414. return;
  71415. }
  71416. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71417. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71418. return;
  71419. }
  71420. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71421. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71422. };
  71423. /**
  71424. * Moves the axis on the controller mesh based on its current state
  71425. * @param axis the index of the axis
  71426. * @param axisValue the value of the axis which determines the meshes new position
  71427. * @hidden
  71428. */
  71429. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71430. if (!this._loadedMeshInfo) {
  71431. return;
  71432. }
  71433. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71434. if (!meshInfo) {
  71435. return;
  71436. }
  71437. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71438. return;
  71439. }
  71440. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71441. var lerpValue = axisValue * 0.5 + 0.5;
  71442. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71443. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71444. };
  71445. /**
  71446. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71447. * @param scene scene in which to add meshes
  71448. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71449. */
  71450. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71451. var _this = this;
  71452. if (forceDefault === void 0) { forceDefault = false; }
  71453. var path;
  71454. var filename;
  71455. // Checking if GLB loader is present
  71456. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71457. // Determine the device specific folder based on the ID suffix
  71458. var device = 'default';
  71459. if (this.id && !forceDefault) {
  71460. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71461. device = ((match && match[0]) || device);
  71462. }
  71463. // Hand
  71464. if (this.hand === 'left') {
  71465. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71466. }
  71467. else { // Right is the default if no hand is specified
  71468. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71469. }
  71470. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71471. }
  71472. else {
  71473. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71474. path = BABYLON.GenericController.MODEL_BASE_URL;
  71475. filename = BABYLON.GenericController.MODEL_FILENAME;
  71476. }
  71477. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71478. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71479. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71480. if (!_this._loadedMeshInfo) {
  71481. return;
  71482. }
  71483. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71484. _this.attachToMesh(_this._defaultModel);
  71485. if (meshLoaded) {
  71486. meshLoaded(_this._defaultModel);
  71487. }
  71488. }, null, function (scene, message) {
  71489. BABYLON.Tools.Log(message);
  71490. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71491. if (!forceDefault) {
  71492. _this.initControllerMesh(scene, meshLoaded, true);
  71493. }
  71494. });
  71495. };
  71496. /**
  71497. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71498. * can be transformed by button presses and axes values, based on this._mapping.
  71499. *
  71500. * @param scene scene in which the meshes exist
  71501. * @param meshes list of meshes that make up the controller model to process
  71502. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71503. */
  71504. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71505. var loadedMeshInfo = null;
  71506. // Create a new mesh to contain the glTF hierarchy
  71507. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71508. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71509. var childMesh = null;
  71510. for (var i = 0; i < meshes.length; i++) {
  71511. var mesh = meshes[i];
  71512. if (!mesh.parent) {
  71513. // Exclude controller meshes from picking results
  71514. mesh.isPickable = false;
  71515. // Handle root node, attach to the new parentMesh
  71516. childMesh = mesh;
  71517. break;
  71518. }
  71519. }
  71520. if (childMesh) {
  71521. childMesh.setParent(parentMesh);
  71522. // Create our mesh info. Note that this method will always return non-null.
  71523. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71524. }
  71525. else {
  71526. BABYLON.Tools.Warn('Could not find root node in model file.');
  71527. }
  71528. return loadedMeshInfo;
  71529. };
  71530. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71531. var loadedMeshInfo = new LoadedMeshInfo();
  71532. var i;
  71533. loadedMeshInfo.rootNode = rootNode;
  71534. // Reset the caches
  71535. loadedMeshInfo.buttonMeshes = {};
  71536. loadedMeshInfo.axisMeshes = {};
  71537. // Button Meshes
  71538. for (i = 0; i < this._mapping.buttons.length; i++) {
  71539. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71540. if (!buttonMeshName) {
  71541. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71542. continue;
  71543. }
  71544. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71545. if (!buttonMesh) {
  71546. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71547. continue;
  71548. }
  71549. var buttonMeshInfo = {
  71550. index: i,
  71551. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71552. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71553. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71554. };
  71555. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71556. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71557. }
  71558. else {
  71559. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71560. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71561. '(VALUE: ' + !!buttonMeshInfo.value +
  71562. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71563. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71564. ')');
  71565. }
  71566. }
  71567. // Axis Meshes
  71568. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71569. var axisMeshName = this._mapping.axisMeshNames[i];
  71570. if (!axisMeshName) {
  71571. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71572. continue;
  71573. }
  71574. var axisMesh = getChildByName(rootNode, axisMeshName);
  71575. if (!axisMesh) {
  71576. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71577. continue;
  71578. }
  71579. var axisMeshInfo = {
  71580. index: i,
  71581. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71582. min: getImmediateChildByName(axisMesh, 'MIN'),
  71583. max: getImmediateChildByName(axisMesh, 'MAX')
  71584. };
  71585. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71586. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71587. }
  71588. else {
  71589. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71590. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71591. '(VALUE: ' + !!axisMeshInfo.value +
  71592. ', MIN: ' + !!axisMeshInfo.min +
  71593. ', MAX:' + !!axisMeshInfo.max +
  71594. ')');
  71595. }
  71596. }
  71597. // Pointing Ray
  71598. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71599. if (!loadedMeshInfo.pointingPoseNode) {
  71600. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71601. }
  71602. return loadedMeshInfo;
  71603. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71604. function getChildByName(node, name) {
  71605. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71606. }
  71607. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71608. function getImmediateChildByName(node, name) {
  71609. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71610. }
  71611. };
  71612. /**
  71613. * Gets the ray of the controller in the direction the controller is pointing
  71614. * @param length the length the resulting ray should be
  71615. * @returns a ray in the direction the controller is pointing
  71616. */
  71617. WindowsMotionController.prototype.getForwardRay = function (length) {
  71618. if (length === void 0) { length = 100; }
  71619. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71620. return _super.prototype.getForwardRay.call(this, length);
  71621. }
  71622. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71623. var origin = m.getTranslation();
  71624. var forward = new BABYLON.Vector3(0, 0, -1);
  71625. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71626. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71627. return new BABYLON.Ray(origin, direction, length);
  71628. };
  71629. /**
  71630. * Disposes of the controller
  71631. */
  71632. WindowsMotionController.prototype.dispose = function () {
  71633. _super.prototype.dispose.call(this);
  71634. this.onTrackpadChangedObservable.clear();
  71635. };
  71636. /**
  71637. * The base url used to load the left and right controller models
  71638. */
  71639. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71640. /**
  71641. * The name of the left controller model file
  71642. */
  71643. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71644. /**
  71645. * The name of the right controller model file
  71646. */
  71647. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71648. /**
  71649. * The controller name prefix for this controller type
  71650. */
  71651. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71652. /**
  71653. * The controller id pattern for this controller type
  71654. */
  71655. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71656. return WindowsMotionController;
  71657. }(BABYLON.WebVRController));
  71658. BABYLON.WindowsMotionController = WindowsMotionController;
  71659. })(BABYLON || (BABYLON = {}));
  71660. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71661. var BABYLON;
  71662. (function (BABYLON) {
  71663. /**
  71664. * Gear VR Controller
  71665. */
  71666. var GearVRController = /** @class */ (function (_super) {
  71667. __extends(GearVRController, _super);
  71668. /**
  71669. * Creates a new GearVRController from a gamepad
  71670. * @param vrGamepad the gamepad that the controller should be created from
  71671. */
  71672. function GearVRController(vrGamepad) {
  71673. var _this = _super.call(this, vrGamepad) || this;
  71674. _this._buttonIndexToObservableNameMap = [
  71675. 'onTrackpadChangedObservable',
  71676. 'onTriggerStateChangedObservable' // Trigger
  71677. ];
  71678. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71679. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  71680. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  71681. return _this;
  71682. }
  71683. /**
  71684. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71685. * @param scene scene in which to add meshes
  71686. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71687. */
  71688. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71689. var _this = this;
  71690. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71691. _this._defaultModel = newMeshes[1];
  71692. _this.attachToMesh(_this._defaultModel);
  71693. if (meshLoaded) {
  71694. meshLoaded(_this._defaultModel);
  71695. }
  71696. });
  71697. };
  71698. /**
  71699. * Called once for each button that changed state since the last frame
  71700. * @param buttonIdx Which button index changed
  71701. * @param state New state of the button
  71702. * @param changes Which properties on the state changed since last frame
  71703. */
  71704. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71705. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71706. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71707. // Only emit events for buttons that we know how to map from index to observable
  71708. var observable = this[observableName];
  71709. if (observable) {
  71710. observable.notifyObservers(state);
  71711. }
  71712. }
  71713. };
  71714. /**
  71715. * Base Url for the controller model.
  71716. */
  71717. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71718. /**
  71719. * File name for the controller model.
  71720. */
  71721. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71722. /**
  71723. * Gamepad Id prefix used to identify this controller.
  71724. */
  71725. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71726. return GearVRController;
  71727. }(BABYLON.WebVRController));
  71728. BABYLON.GearVRController = GearVRController;
  71729. })(BABYLON || (BABYLON = {}));
  71730. //# sourceMappingURL=babylon.gearVRController.js.map
  71731. var BABYLON;
  71732. (function (BABYLON) {
  71733. /**
  71734. * Google Daydream controller
  71735. */
  71736. var DaydreamController = /** @class */ (function (_super) {
  71737. __extends(DaydreamController, _super);
  71738. /**
  71739. * Creates a new DaydreamController from a gamepad
  71740. * @param vrGamepad the gamepad that the controller should be created from
  71741. */
  71742. function DaydreamController(vrGamepad) {
  71743. var _this = _super.call(this, vrGamepad) || this;
  71744. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  71745. return _this;
  71746. }
  71747. /**
  71748. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71749. * @param scene scene in which to add meshes
  71750. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71751. */
  71752. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71753. var _this = this;
  71754. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  71755. _this._defaultModel = newMeshes[1];
  71756. _this.attachToMesh(_this._defaultModel);
  71757. if (meshLoaded) {
  71758. meshLoaded(_this._defaultModel);
  71759. }
  71760. });
  71761. };
  71762. /**
  71763. * Called once for each button that changed state since the last frame
  71764. * @param buttonIdx Which button index changed
  71765. * @param state New state of the button
  71766. * @param changes Which properties on the state changed since last frame
  71767. */
  71768. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71769. // Daydream controller only has 1 GamepadButton (on the trackpad).
  71770. if (buttonIdx === 0) {
  71771. var observable = this.onTriggerStateChangedObservable;
  71772. if (observable) {
  71773. observable.notifyObservers(state);
  71774. }
  71775. }
  71776. else {
  71777. // If the app or home buttons are ever made available
  71778. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  71779. }
  71780. };
  71781. /**
  71782. * Base Url for the controller model.
  71783. */
  71784. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71785. /**
  71786. * File name for the controller model.
  71787. */
  71788. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  71789. /**
  71790. * Gamepad Id prefix used to identify Daydream Controller.
  71791. */
  71792. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  71793. return DaydreamController;
  71794. }(BABYLON.WebVRController));
  71795. BABYLON.DaydreamController = DaydreamController;
  71796. })(BABYLON || (BABYLON = {}));
  71797. //# sourceMappingURL=babylon.daydreamController.js.map
  71798. var BABYLON;
  71799. (function (BABYLON) {
  71800. var FollowCamera = /** @class */ (function (_super) {
  71801. __extends(FollowCamera, _super);
  71802. function FollowCamera(name, position, scene, lockedTarget) {
  71803. if (lockedTarget === void 0) { lockedTarget = null; }
  71804. var _this = _super.call(this, name, position, scene) || this;
  71805. _this.radius = 12;
  71806. _this.rotationOffset = 0;
  71807. _this.heightOffset = 4;
  71808. _this.cameraAcceleration = 0.05;
  71809. _this.maxCameraSpeed = 20;
  71810. _this.lockedTarget = lockedTarget;
  71811. return _this;
  71812. }
  71813. FollowCamera.prototype.getRadians = function (degrees) {
  71814. return degrees * Math.PI / 180;
  71815. };
  71816. FollowCamera.prototype.follow = function (cameraTarget) {
  71817. if (!cameraTarget)
  71818. return;
  71819. var yRotation;
  71820. if (cameraTarget.rotationQuaternion) {
  71821. var rotMatrix = new BABYLON.Matrix();
  71822. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  71823. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  71824. }
  71825. else {
  71826. yRotation = cameraTarget.rotation.y;
  71827. }
  71828. var radians = this.getRadians(this.rotationOffset) + yRotation;
  71829. var targetPosition = cameraTarget.getAbsolutePosition();
  71830. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  71831. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  71832. var dx = targetX - this.position.x;
  71833. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  71834. var dz = (targetZ) - this.position.z;
  71835. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  71836. var vy = dy * this.cameraAcceleration;
  71837. var vz = dz * this.cameraAcceleration * 2;
  71838. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  71839. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71840. }
  71841. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  71842. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71843. }
  71844. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  71845. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71846. }
  71847. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  71848. this.setTarget(targetPosition);
  71849. };
  71850. FollowCamera.prototype._checkInputs = function () {
  71851. _super.prototype._checkInputs.call(this);
  71852. if (this.lockedTarget) {
  71853. this.follow(this.lockedTarget);
  71854. }
  71855. };
  71856. FollowCamera.prototype.getClassName = function () {
  71857. return "FollowCamera";
  71858. };
  71859. __decorate([
  71860. BABYLON.serialize()
  71861. ], FollowCamera.prototype, "radius", void 0);
  71862. __decorate([
  71863. BABYLON.serialize()
  71864. ], FollowCamera.prototype, "rotationOffset", void 0);
  71865. __decorate([
  71866. BABYLON.serialize()
  71867. ], FollowCamera.prototype, "heightOffset", void 0);
  71868. __decorate([
  71869. BABYLON.serialize()
  71870. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  71871. __decorate([
  71872. BABYLON.serialize()
  71873. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  71874. __decorate([
  71875. BABYLON.serializeAsMeshReference("lockedTargetId")
  71876. ], FollowCamera.prototype, "lockedTarget", void 0);
  71877. return FollowCamera;
  71878. }(BABYLON.TargetCamera));
  71879. BABYLON.FollowCamera = FollowCamera;
  71880. var ArcFollowCamera = /** @class */ (function (_super) {
  71881. __extends(ArcFollowCamera, _super);
  71882. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  71883. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  71884. _this.alpha = alpha;
  71885. _this.beta = beta;
  71886. _this.radius = radius;
  71887. _this.target = target;
  71888. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  71889. _this.follow();
  71890. return _this;
  71891. }
  71892. ArcFollowCamera.prototype.follow = function () {
  71893. if (!this.target) {
  71894. return;
  71895. }
  71896. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  71897. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  71898. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  71899. var targetPosition = this.target.getAbsolutePosition();
  71900. this.position = targetPosition.add(this._cartesianCoordinates);
  71901. this.setTarget(targetPosition);
  71902. };
  71903. ArcFollowCamera.prototype._checkInputs = function () {
  71904. _super.prototype._checkInputs.call(this);
  71905. this.follow();
  71906. };
  71907. ArcFollowCamera.prototype.getClassName = function () {
  71908. return "ArcFollowCamera";
  71909. };
  71910. return ArcFollowCamera;
  71911. }(BABYLON.TargetCamera));
  71912. BABYLON.ArcFollowCamera = ArcFollowCamera;
  71913. })(BABYLON || (BABYLON = {}));
  71914. //# sourceMappingURL=babylon.followCamera.js.map
  71915. var BABYLON;
  71916. (function (BABYLON) {
  71917. // We're mainly based on the logic defined into the FreeCamera code
  71918. var UniversalCamera = /** @class */ (function (_super) {
  71919. __extends(UniversalCamera, _super);
  71920. //-- end properties for backward compatibility for inputs
  71921. function UniversalCamera(name, position, scene) {
  71922. var _this = _super.call(this, name, position, scene) || this;
  71923. _this.inputs.addGamepad();
  71924. return _this;
  71925. }
  71926. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  71927. //-- Begin properties for backward compatibility for inputs
  71928. get: function () {
  71929. var gamepad = this.inputs.attached["gamepad"];
  71930. if (gamepad)
  71931. return gamepad.gamepadAngularSensibility;
  71932. return 0;
  71933. },
  71934. set: function (value) {
  71935. var gamepad = this.inputs.attached["gamepad"];
  71936. if (gamepad)
  71937. gamepad.gamepadAngularSensibility = value;
  71938. },
  71939. enumerable: true,
  71940. configurable: true
  71941. });
  71942. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  71943. get: function () {
  71944. var gamepad = this.inputs.attached["gamepad"];
  71945. if (gamepad)
  71946. return gamepad.gamepadMoveSensibility;
  71947. return 0;
  71948. },
  71949. set: function (value) {
  71950. var gamepad = this.inputs.attached["gamepad"];
  71951. if (gamepad)
  71952. gamepad.gamepadMoveSensibility = value;
  71953. },
  71954. enumerable: true,
  71955. configurable: true
  71956. });
  71957. UniversalCamera.prototype.getClassName = function () {
  71958. return "UniversalCamera";
  71959. };
  71960. return UniversalCamera;
  71961. }(BABYLON.TouchCamera));
  71962. BABYLON.UniversalCamera = UniversalCamera;
  71963. })(BABYLON || (BABYLON = {}));
  71964. //# sourceMappingURL=babylon.universalCamera.js.map
  71965. var BABYLON;
  71966. (function (BABYLON) {
  71967. // We're mainly based on the logic defined into the FreeCamera code
  71968. var GamepadCamera = /** @class */ (function (_super) {
  71969. __extends(GamepadCamera, _super);
  71970. //-- end properties for backward compatibility for inputs
  71971. function GamepadCamera(name, position, scene) {
  71972. return _super.call(this, name, position, scene) || this;
  71973. }
  71974. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  71975. //-- Begin properties for backward compatibility for inputs
  71976. get: function () {
  71977. var gamepad = this.inputs.attached["gamepad"];
  71978. if (gamepad)
  71979. return gamepad.gamepadAngularSensibility;
  71980. return 0;
  71981. },
  71982. set: function (value) {
  71983. var gamepad = this.inputs.attached["gamepad"];
  71984. if (gamepad)
  71985. gamepad.gamepadAngularSensibility = value;
  71986. },
  71987. enumerable: true,
  71988. configurable: true
  71989. });
  71990. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  71991. get: function () {
  71992. var gamepad = this.inputs.attached["gamepad"];
  71993. if (gamepad)
  71994. return gamepad.gamepadMoveSensibility;
  71995. return 0;
  71996. },
  71997. set: function (value) {
  71998. var gamepad = this.inputs.attached["gamepad"];
  71999. if (gamepad)
  72000. gamepad.gamepadMoveSensibility = value;
  72001. },
  72002. enumerable: true,
  72003. configurable: true
  72004. });
  72005. GamepadCamera.prototype.getClassName = function () {
  72006. return "GamepadCamera";
  72007. };
  72008. return GamepadCamera;
  72009. }(BABYLON.UniversalCamera));
  72010. BABYLON.GamepadCamera = GamepadCamera;
  72011. })(BABYLON || (BABYLON = {}));
  72012. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72013. var BABYLON;
  72014. (function (BABYLON) {
  72015. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72016. function PostProcessRenderPipelineManager() {
  72017. this._renderPipelines = {};
  72018. }
  72019. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72020. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72021. };
  72022. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72023. if (unique === void 0) { unique = false; }
  72024. var renderPipeline = this._renderPipelines[renderPipelineName];
  72025. if (!renderPipeline) {
  72026. return;
  72027. }
  72028. renderPipeline._attachCameras(cameras, unique);
  72029. };
  72030. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72031. var renderPipeline = this._renderPipelines[renderPipelineName];
  72032. if (!renderPipeline) {
  72033. return;
  72034. }
  72035. renderPipeline._detachCameras(cameras);
  72036. };
  72037. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72038. var renderPipeline = this._renderPipelines[renderPipelineName];
  72039. if (!renderPipeline) {
  72040. return;
  72041. }
  72042. renderPipeline._enableEffect(renderEffectName, cameras);
  72043. };
  72044. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72045. var renderPipeline = this._renderPipelines[renderPipelineName];
  72046. if (!renderPipeline) {
  72047. return;
  72048. }
  72049. renderPipeline._disableEffect(renderEffectName, cameras);
  72050. };
  72051. PostProcessRenderPipelineManager.prototype.update = function () {
  72052. for (var renderPipelineName in this._renderPipelines) {
  72053. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72054. var pipeline = this._renderPipelines[renderPipelineName];
  72055. if (!pipeline.isSupported) {
  72056. pipeline.dispose();
  72057. delete this._renderPipelines[renderPipelineName];
  72058. }
  72059. else {
  72060. pipeline._update();
  72061. }
  72062. }
  72063. }
  72064. };
  72065. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72066. for (var renderPipelineName in this._renderPipelines) {
  72067. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72068. var pipeline = this._renderPipelines[renderPipelineName];
  72069. pipeline._rebuild();
  72070. }
  72071. }
  72072. };
  72073. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72074. for (var renderPipelineName in this._renderPipelines) {
  72075. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72076. var pipeline = this._renderPipelines[renderPipelineName];
  72077. pipeline.dispose();
  72078. }
  72079. }
  72080. };
  72081. return PostProcessRenderPipelineManager;
  72082. }());
  72083. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72084. })(BABYLON || (BABYLON = {}));
  72085. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72086. var BABYLON;
  72087. (function (BABYLON) {
  72088. /**
  72089. * This represents a set of one or more post processes in Babylon.
  72090. * A post process can be used to apply a shader to a texture after it is rendered.
  72091. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72092. */
  72093. var PostProcessRenderEffect = /** @class */ (function () {
  72094. /**
  72095. * Instantiates a post process render effect.
  72096. * A post process can be used to apply a shader to a texture after it is rendered.
  72097. * @param engine The engine the effect is tied to
  72098. * @param name The name of the effect
  72099. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72100. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72101. */
  72102. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72103. this._name = name;
  72104. this._singleInstance = singleInstance || true;
  72105. this._getPostProcesses = getPostProcesses;
  72106. this._cameras = {};
  72107. this._indicesForCamera = {};
  72108. this._postProcesses = {};
  72109. }
  72110. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72111. /**
  72112. * Checks if all the post processes in the effect are supported.
  72113. */
  72114. get: function () {
  72115. for (var index in this._postProcesses) {
  72116. if (this._postProcesses.hasOwnProperty(index)) {
  72117. var pps = this._postProcesses[index];
  72118. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72119. if (!pps[ppIndex].isSupported) {
  72120. return false;
  72121. }
  72122. }
  72123. }
  72124. }
  72125. return true;
  72126. },
  72127. enumerable: true,
  72128. configurable: true
  72129. });
  72130. /**
  72131. * Updates the current state of the effect
  72132. */
  72133. PostProcessRenderEffect.prototype._update = function () {
  72134. };
  72135. /**
  72136. * Attaches the effect on cameras
  72137. * @param cameras The camera to attach to.
  72138. */
  72139. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72140. var _this = this;
  72141. var cameraKey;
  72142. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72143. if (!cams) {
  72144. return;
  72145. }
  72146. for (var i = 0; i < cams.length; i++) {
  72147. var camera = cams[i];
  72148. var cameraName = camera.name;
  72149. if (this._singleInstance) {
  72150. cameraKey = 0;
  72151. }
  72152. else {
  72153. cameraKey = cameraName;
  72154. }
  72155. if (!this._postProcesses[cameraKey]) {
  72156. var postProcess = this._getPostProcesses();
  72157. if (postProcess) {
  72158. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72159. }
  72160. }
  72161. if (!this._indicesForCamera[cameraName]) {
  72162. this._indicesForCamera[cameraName] = [];
  72163. }
  72164. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72165. var index = camera.attachPostProcess(postProcess);
  72166. _this._indicesForCamera[cameraName].push(index);
  72167. });
  72168. if (!this._cameras[cameraName]) {
  72169. this._cameras[cameraName] = camera;
  72170. }
  72171. }
  72172. };
  72173. /**
  72174. * Detatches the effect on cameras
  72175. * @param cameras The camera to detatch from.
  72176. */
  72177. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72178. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72179. if (!cams) {
  72180. return;
  72181. }
  72182. for (var i = 0; i < cams.length; i++) {
  72183. var camera = cams[i];
  72184. var cameraName = camera.name;
  72185. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72186. camera.detachPostProcess(postProcess);
  72187. });
  72188. if (this._cameras[cameraName]) {
  72189. //this._indicesForCamera.splice(index, 1);
  72190. this._cameras[cameraName] = null;
  72191. }
  72192. }
  72193. };
  72194. /**
  72195. * Enables the effect on given cameras
  72196. * @param cameras The camera to enable.
  72197. */
  72198. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72199. var _this = this;
  72200. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72201. if (!cams) {
  72202. return;
  72203. }
  72204. for (var i = 0; i < cams.length; i++) {
  72205. var camera = cams[i];
  72206. var cameraName = camera.name;
  72207. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72208. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72209. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72210. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72211. });
  72212. }
  72213. }
  72214. }
  72215. };
  72216. /**
  72217. * Disables the effect on the given cameras
  72218. * @param cameras The camera to disable.
  72219. */
  72220. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72221. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72222. if (!cams) {
  72223. return;
  72224. }
  72225. for (var i = 0; i < cams.length; i++) {
  72226. var camera = cams[i];
  72227. var cameraName = camera.name;
  72228. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72229. camera.detachPostProcess(postProcess);
  72230. });
  72231. }
  72232. };
  72233. /**
  72234. * Gets a list of the post processes contained in the effect.
  72235. * @param camera The camera to get the post processes on.
  72236. * @returns The list of the post processes in the effect.
  72237. */
  72238. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72239. if (this._singleInstance) {
  72240. return this._postProcesses[0];
  72241. }
  72242. else {
  72243. if (!camera) {
  72244. return null;
  72245. }
  72246. return this._postProcesses[camera.name];
  72247. }
  72248. };
  72249. return PostProcessRenderEffect;
  72250. }());
  72251. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72252. })(BABYLON || (BABYLON = {}));
  72253. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72254. var BABYLON;
  72255. (function (BABYLON) {
  72256. var PostProcessRenderPipeline = /** @class */ (function () {
  72257. function PostProcessRenderPipeline(engine, name) {
  72258. this.engine = engine;
  72259. this._name = name;
  72260. this._renderEffects = {};
  72261. this._renderEffectsForIsolatedPass = new Array();
  72262. this._cameras = [];
  72263. }
  72264. PostProcessRenderPipeline.prototype.getClassName = function () {
  72265. return "PostProcessRenderPipeline";
  72266. };
  72267. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72268. get: function () {
  72269. for (var renderEffectName in this._renderEffects) {
  72270. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72271. if (!this._renderEffects[renderEffectName].isSupported) {
  72272. return false;
  72273. }
  72274. }
  72275. }
  72276. return true;
  72277. },
  72278. enumerable: true,
  72279. configurable: true
  72280. });
  72281. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72282. this._renderEffects[renderEffect._name] = renderEffect;
  72283. };
  72284. // private
  72285. PostProcessRenderPipeline.prototype._rebuild = function () {
  72286. };
  72287. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72288. var renderEffects = this._renderEffects[renderEffectName];
  72289. if (!renderEffects) {
  72290. return;
  72291. }
  72292. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72293. };
  72294. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72295. var renderEffects = this._renderEffects[renderEffectName];
  72296. if (!renderEffects) {
  72297. return;
  72298. }
  72299. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72300. };
  72301. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72302. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72303. if (!cams) {
  72304. return;
  72305. }
  72306. var indicesToDelete = [];
  72307. var i;
  72308. for (i = 0; i < cams.length; i++) {
  72309. var camera = cams[i];
  72310. var cameraName = camera.name;
  72311. if (this._cameras.indexOf(camera) === -1) {
  72312. this._cameras[cameraName] = camera;
  72313. }
  72314. else if (unique) {
  72315. indicesToDelete.push(i);
  72316. }
  72317. }
  72318. for (i = 0; i < indicesToDelete.length; i++) {
  72319. cameras.splice(indicesToDelete[i], 1);
  72320. }
  72321. for (var renderEffectName in this._renderEffects) {
  72322. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72323. this._renderEffects[renderEffectName]._attachCameras(cams);
  72324. }
  72325. }
  72326. };
  72327. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72328. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72329. if (!cams) {
  72330. return;
  72331. }
  72332. for (var renderEffectName in this._renderEffects) {
  72333. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72334. this._renderEffects[renderEffectName]._detachCameras(cams);
  72335. }
  72336. }
  72337. for (var i = 0; i < cams.length; i++) {
  72338. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72339. }
  72340. };
  72341. PostProcessRenderPipeline.prototype._update = function () {
  72342. for (var renderEffectName in this._renderEffects) {
  72343. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72344. this._renderEffects[renderEffectName]._update();
  72345. }
  72346. }
  72347. for (var i = 0; i < this._cameras.length; i++) {
  72348. var cameraName = this._cameras[i].name;
  72349. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72350. this._renderEffectsForIsolatedPass[cameraName]._update();
  72351. }
  72352. }
  72353. };
  72354. PostProcessRenderPipeline.prototype._reset = function () {
  72355. this._renderEffects = {};
  72356. this._renderEffectsForIsolatedPass = new Array();
  72357. };
  72358. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72359. // 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)
  72360. var effectKeys = Object.keys(this._renderEffects);
  72361. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72362. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72363. if (postProcesses) {
  72364. postProcesses[0].samples = sampleCount;
  72365. return true;
  72366. }
  72367. }
  72368. return false;
  72369. };
  72370. PostProcessRenderPipeline.prototype.dispose = function () {
  72371. // Must be implemented by children
  72372. };
  72373. __decorate([
  72374. BABYLON.serialize()
  72375. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72376. return PostProcessRenderPipeline;
  72377. }());
  72378. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72379. })(BABYLON || (BABYLON = {}));
  72380. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72381. var BABYLON;
  72382. (function (BABYLON) {
  72383. /**
  72384. * This represents a depth renderer in Babylon.
  72385. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72386. */
  72387. var DepthRenderer = /** @class */ (function () {
  72388. /**
  72389. * Instantiates a depth renderer
  72390. * @param scene The scene the renderer belongs to
  72391. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72392. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72393. */
  72394. function DepthRenderer(scene, type, camera) {
  72395. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72396. if (camera === void 0) { camera = null; }
  72397. var _this = this;
  72398. this._scene = scene;
  72399. this._camera = camera;
  72400. var engine = scene.getEngine();
  72401. // Render target
  72402. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72403. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72404. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72405. this._depthMap.refreshRate = 1;
  72406. this._depthMap.renderParticles = false;
  72407. this._depthMap.renderList = null;
  72408. // Camera to get depth map from to support multiple concurrent cameras
  72409. this._depthMap.activeCamera = this._camera;
  72410. this._depthMap.ignoreCameraViewport = true;
  72411. this._depthMap.useCameraPostProcesses = false;
  72412. // set default depth value to 1.0 (far away)
  72413. this._depthMap.onClearObservable.add(function (engine) {
  72414. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72415. });
  72416. // Custom render function
  72417. var renderSubMesh = function (subMesh) {
  72418. var mesh = subMesh.getRenderingMesh();
  72419. var scene = _this._scene;
  72420. var engine = scene.getEngine();
  72421. var material = subMesh.getMaterial();
  72422. if (!material) {
  72423. return;
  72424. }
  72425. // Culling and reverse (right handed system)
  72426. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72427. // Managing instances
  72428. var batch = mesh._getInstancesRenderList(subMesh._id);
  72429. if (batch.mustReturn) {
  72430. return;
  72431. }
  72432. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72433. var camera = _this._camera || scene.activeCamera;
  72434. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72435. engine.enableEffect(_this._effect);
  72436. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72437. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72438. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72439. // Alpha test
  72440. if (material && material.needAlphaTesting()) {
  72441. var alphaTexture = material.getAlphaTestTexture();
  72442. if (alphaTexture) {
  72443. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72444. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72445. }
  72446. }
  72447. // Bones
  72448. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72449. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72450. }
  72451. // Draw
  72452. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72453. }
  72454. };
  72455. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72456. var index;
  72457. if (depthOnlySubMeshes.length) {
  72458. engine.setColorWrite(false);
  72459. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72460. renderSubMesh(depthOnlySubMeshes.data[index]);
  72461. }
  72462. engine.setColorWrite(true);
  72463. }
  72464. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72465. renderSubMesh(opaqueSubMeshes.data[index]);
  72466. }
  72467. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72468. renderSubMesh(alphaTestSubMeshes.data[index]);
  72469. }
  72470. };
  72471. }
  72472. /**
  72473. * Creates the depth rendering effect and checks if the effect is ready.
  72474. * @param subMesh The submesh to be used to render the depth map of
  72475. * @param useInstances If multiple world instances should be used
  72476. * @returns if the depth renderer is ready to render the depth map
  72477. */
  72478. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72479. var material = subMesh.getMaterial();
  72480. if (material.disableDepthWrite) {
  72481. return false;
  72482. }
  72483. var defines = [];
  72484. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72485. var mesh = subMesh.getMesh();
  72486. // Alpha test
  72487. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72488. defines.push("#define ALPHATEST");
  72489. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72490. attribs.push(BABYLON.VertexBuffer.UVKind);
  72491. defines.push("#define UV1");
  72492. }
  72493. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72494. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72495. defines.push("#define UV2");
  72496. }
  72497. }
  72498. // Bones
  72499. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72500. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72501. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72502. if (mesh.numBoneInfluencers > 4) {
  72503. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72504. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72505. }
  72506. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72507. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72508. }
  72509. else {
  72510. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72511. }
  72512. // Instances
  72513. if (useInstances) {
  72514. defines.push("#define INSTANCES");
  72515. attribs.push("world0");
  72516. attribs.push("world1");
  72517. attribs.push("world2");
  72518. attribs.push("world3");
  72519. }
  72520. // Get correct effect
  72521. var join = defines.join("\n");
  72522. if (this._cachedDefines !== join) {
  72523. this._cachedDefines = join;
  72524. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72525. }
  72526. return this._effect.isReady();
  72527. };
  72528. /**
  72529. * Gets the texture which the depth map will be written to.
  72530. * @returns The depth map texture
  72531. */
  72532. DepthRenderer.prototype.getDepthMap = function () {
  72533. return this._depthMap;
  72534. };
  72535. /**
  72536. * Disposes of the depth renderer.
  72537. */
  72538. DepthRenderer.prototype.dispose = function () {
  72539. this._depthMap.dispose();
  72540. };
  72541. return DepthRenderer;
  72542. }());
  72543. BABYLON.DepthRenderer = DepthRenderer;
  72544. })(BABYLON || (BABYLON = {}));
  72545. //# sourceMappingURL=babylon.depthRenderer.js.map
  72546. var BABYLON;
  72547. (function (BABYLON) {
  72548. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72549. __extends(SSAORenderingPipeline, _super);
  72550. /**
  72551. * @constructor
  72552. * @param {string} name - The rendering pipeline name
  72553. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72554. * @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 }
  72555. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72556. */
  72557. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72558. var _this = _super.call(this, scene.getEngine(), name) || this;
  72559. // Members
  72560. /**
  72561. * The PassPostProcess id in the pipeline that contains the original scene color
  72562. */
  72563. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72564. /**
  72565. * The SSAO PostProcess id in the pipeline
  72566. */
  72567. _this.SSAORenderEffect = "SSAORenderEffect";
  72568. /**
  72569. * The horizontal blur PostProcess id in the pipeline
  72570. */
  72571. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72572. /**
  72573. * The vertical blur PostProcess id in the pipeline
  72574. */
  72575. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72576. /**
  72577. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72578. */
  72579. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72580. /**
  72581. * The output strength of the SSAO post-process. Default value is 1.0.
  72582. */
  72583. _this.totalStrength = 1.0;
  72584. /**
  72585. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72586. */
  72587. _this.radius = 0.0001;
  72588. /**
  72589. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72590. * Must not be equal to fallOff and superior to fallOff.
  72591. * Default value is 0.975
  72592. */
  72593. _this.area = 0.0075;
  72594. /**
  72595. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72596. * Must not be equal to area and inferior to area.
  72597. * Default value is 0.0
  72598. */
  72599. _this.fallOff = 0.000001;
  72600. /**
  72601. * The base color of the SSAO post-process
  72602. * The final result is "base + ssao" between [0, 1]
  72603. */
  72604. _this.base = 0.5;
  72605. _this._firstUpdate = true;
  72606. _this._scene = scene;
  72607. // Set up assets
  72608. _this._createRandomTexture();
  72609. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72610. var ssaoRatio = ratio.ssaoRatio || ratio;
  72611. var combineRatio = ratio.combineRatio || ratio;
  72612. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72613. _this._createSSAOPostProcess(ssaoRatio);
  72614. _this._createBlurPostProcess(ssaoRatio);
  72615. _this._createSSAOCombinePostProcess(combineRatio);
  72616. // Set up pipeline
  72617. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72618. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72619. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72620. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72621. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72622. // Finish
  72623. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72624. if (cameras)
  72625. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72626. return _this;
  72627. }
  72628. // Public Methods
  72629. /**
  72630. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72631. */
  72632. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72633. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72634. for (var i = 0; i < this._scene.cameras.length; i++) {
  72635. var camera = this._scene.cameras[i];
  72636. this._originalColorPostProcess.dispose(camera);
  72637. this._ssaoPostProcess.dispose(camera);
  72638. this._blurHPostProcess.dispose(camera);
  72639. this._blurVPostProcess.dispose(camera);
  72640. this._ssaoCombinePostProcess.dispose(camera);
  72641. }
  72642. this._randomTexture.dispose();
  72643. if (disableDepthRender)
  72644. this._scene.disableDepthRenderer();
  72645. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72646. _super.prototype.dispose.call(this);
  72647. };
  72648. // Private Methods
  72649. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72650. var _this = this;
  72651. var size = 16;
  72652. 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);
  72653. 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);
  72654. this._blurHPostProcess.onActivateObservable.add(function () {
  72655. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72656. _this._blurHPostProcess.kernel = size * dw;
  72657. });
  72658. this._blurVPostProcess.onActivateObservable.add(function () {
  72659. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72660. _this._blurVPostProcess.kernel = size * dw;
  72661. });
  72662. };
  72663. SSAORenderingPipeline.prototype._rebuild = function () {
  72664. this._firstUpdate = true;
  72665. _super.prototype._rebuild.call(this);
  72666. };
  72667. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72668. var _this = this;
  72669. var numSamples = 16;
  72670. var sampleSphere = [
  72671. 0.5381, 0.1856, -0.4319,
  72672. 0.1379, 0.2486, 0.4430,
  72673. 0.3371, 0.5679, -0.0057,
  72674. -0.6999, -0.0451, -0.0019,
  72675. 0.0689, -0.1598, -0.8547,
  72676. 0.0560, 0.0069, -0.1843,
  72677. -0.0146, 0.1402, 0.0762,
  72678. 0.0100, -0.1924, -0.0344,
  72679. -0.3577, -0.5301, -0.4358,
  72680. -0.3169, 0.1063, 0.0158,
  72681. 0.0103, -0.5869, 0.0046,
  72682. -0.0897, -0.4940, 0.3287,
  72683. 0.7119, -0.0154, -0.0918,
  72684. -0.0533, 0.0596, -0.5411,
  72685. 0.0352, -0.0631, 0.5460,
  72686. -0.4776, 0.2847, -0.0271
  72687. ];
  72688. var samplesFactor = 1.0 / numSamples;
  72689. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72690. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72691. "area", "fallOff", "base", "range", "viewport"
  72692. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72693. this._ssaoPostProcess.onApply = function (effect) {
  72694. if (_this._firstUpdate) {
  72695. effect.setArray3("sampleSphere", sampleSphere);
  72696. effect.setFloat("samplesFactor", samplesFactor);
  72697. effect.setFloat("randTextureTiles", 4.0);
  72698. }
  72699. effect.setFloat("totalStrength", _this.totalStrength);
  72700. effect.setFloat("radius", _this.radius);
  72701. effect.setFloat("area", _this.area);
  72702. effect.setFloat("fallOff", _this.fallOff);
  72703. effect.setFloat("base", _this.base);
  72704. effect.setTexture("textureSampler", _this._depthTexture);
  72705. effect.setTexture("randomSampler", _this._randomTexture);
  72706. };
  72707. };
  72708. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72709. var _this = this;
  72710. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72711. this._ssaoCombinePostProcess.onApply = function (effect) {
  72712. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  72713. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72714. };
  72715. };
  72716. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72717. var size = 512;
  72718. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72719. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72720. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72721. var context = this._randomTexture.getContext();
  72722. var rand = function (min, max) {
  72723. return Math.random() * (max - min) + min;
  72724. };
  72725. var randVector = BABYLON.Vector3.Zero();
  72726. for (var x = 0; x < size; x++) {
  72727. for (var y = 0; y < size; y++) {
  72728. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72729. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72730. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72731. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72732. context.fillRect(x, y, 1, 1);
  72733. }
  72734. }
  72735. this._randomTexture.update(false);
  72736. };
  72737. __decorate([
  72738. BABYLON.serialize()
  72739. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  72740. __decorate([
  72741. BABYLON.serialize()
  72742. ], SSAORenderingPipeline.prototype, "radius", void 0);
  72743. __decorate([
  72744. BABYLON.serialize()
  72745. ], SSAORenderingPipeline.prototype, "area", void 0);
  72746. __decorate([
  72747. BABYLON.serialize()
  72748. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  72749. __decorate([
  72750. BABYLON.serialize()
  72751. ], SSAORenderingPipeline.prototype, "base", void 0);
  72752. return SSAORenderingPipeline;
  72753. }(BABYLON.PostProcessRenderPipeline));
  72754. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  72755. })(BABYLON || (BABYLON = {}));
  72756. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  72757. var BABYLON;
  72758. (function (BABYLON) {
  72759. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  72760. __extends(SSAO2RenderingPipeline, _super);
  72761. /**
  72762. * @constructor
  72763. * @param {string} name - The rendering pipeline name
  72764. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72765. * @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 }
  72766. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72767. */
  72768. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  72769. var _this = _super.call(this, scene.getEngine(), name) || this;
  72770. // Members
  72771. /**
  72772. * The PassPostProcess id in the pipeline that contains the original scene color
  72773. */
  72774. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72775. /**
  72776. * The SSAO PostProcess id in the pipeline
  72777. */
  72778. _this.SSAORenderEffect = "SSAORenderEffect";
  72779. /**
  72780. * The horizontal blur PostProcess id in the pipeline
  72781. */
  72782. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72783. /**
  72784. * The vertical blur PostProcess id in the pipeline
  72785. */
  72786. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72787. /**
  72788. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72789. */
  72790. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72791. /**
  72792. * The output strength of the SSAO post-process. Default value is 1.0.
  72793. */
  72794. _this.totalStrength = 1.0;
  72795. /**
  72796. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  72797. */
  72798. _this.maxZ = 100.0;
  72799. /**
  72800. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  72801. */
  72802. _this.minZAspect = 0.2;
  72803. /**
  72804. * Number of samples used for the SSAO calculations. Default value is 8
  72805. */
  72806. _this._samples = 8;
  72807. /**
  72808. * Are we using bilateral blur ?
  72809. */
  72810. _this._expensiveBlur = true;
  72811. /**
  72812. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  72813. */
  72814. _this.radius = 2.0;
  72815. /**
  72816. * The base color of the SSAO post-process
  72817. * The final result is "base + ssao" between [0, 1]
  72818. */
  72819. _this.base = 0.1;
  72820. _this._firstUpdate = true;
  72821. _this._scene = scene;
  72822. _this._ratio = ratio;
  72823. if (!_this.isSupported) {
  72824. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  72825. return _this;
  72826. }
  72827. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  72828. var blurRatio = _this._ratio.blurRatio || ratio;
  72829. // Set up assets
  72830. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  72831. _this._createRandomTexture();
  72832. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  72833. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  72834. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72835. _this._createSSAOPostProcess(1.0);
  72836. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  72837. _this._createSSAOCombinePostProcess(blurRatio);
  72838. // Set up pipeline
  72839. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72840. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72841. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72842. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72843. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72844. // Finish
  72845. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72846. if (cameras)
  72847. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72848. return _this;
  72849. }
  72850. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  72851. get: function () {
  72852. return this._samples;
  72853. },
  72854. set: function (n) {
  72855. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  72856. this._samples = n;
  72857. this._sampleSphere = this._generateHemisphere();
  72858. this._firstUpdate = true;
  72859. },
  72860. enumerable: true,
  72861. configurable: true
  72862. });
  72863. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  72864. get: function () {
  72865. return this._expensiveBlur;
  72866. },
  72867. set: function (b) {
  72868. 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"]);
  72869. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  72870. this._expensiveBlur = b;
  72871. this._firstUpdate = true;
  72872. },
  72873. enumerable: true,
  72874. configurable: true
  72875. });
  72876. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  72877. /**
  72878. * Support test.
  72879. */
  72880. get: function () {
  72881. var engine = BABYLON.Engine.LastCreatedEngine;
  72882. if (!engine) {
  72883. return false;
  72884. }
  72885. return engine.getCaps().drawBuffersExtension;
  72886. },
  72887. enumerable: true,
  72888. configurable: true
  72889. });
  72890. // Public Methods
  72891. /**
  72892. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72893. */
  72894. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  72895. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  72896. for (var i = 0; i < this._scene.cameras.length; i++) {
  72897. var camera = this._scene.cameras[i];
  72898. this._originalColorPostProcess.dispose(camera);
  72899. this._ssaoPostProcess.dispose(camera);
  72900. this._blurHPostProcess.dispose(camera);
  72901. this._blurVPostProcess.dispose(camera);
  72902. this._ssaoCombinePostProcess.dispose(camera);
  72903. }
  72904. this._randomTexture.dispose();
  72905. if (disableGeometryBufferRenderer)
  72906. this._scene.disableGeometryBufferRenderer();
  72907. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72908. _super.prototype.dispose.call(this);
  72909. };
  72910. // Private Methods
  72911. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72912. var _this = this;
  72913. this._samplerOffsets = [];
  72914. var expensive = this.expensiveBlur;
  72915. for (var i = -8; i < 8; i++) {
  72916. this._samplerOffsets.push(i * 2 + 0.5);
  72917. }
  72918. 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");
  72919. this._blurHPostProcess.onApply = function (effect) {
  72920. if (!_this._scene.activeCamera) {
  72921. return;
  72922. }
  72923. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  72924. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72925. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72926. effect.setFloat("radius", _this.radius);
  72927. effect.setTexture("depthSampler", _this._depthTexture);
  72928. if (_this._firstUpdate) {
  72929. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72930. }
  72931. };
  72932. 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");
  72933. this._blurVPostProcess.onApply = function (effect) {
  72934. if (!_this._scene.activeCamera) {
  72935. return;
  72936. }
  72937. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  72938. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72939. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72940. effect.setFloat("radius", _this.radius);
  72941. effect.setTexture("depthSampler", _this._depthTexture);
  72942. if (_this._firstUpdate) {
  72943. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72944. _this._firstUpdate = false;
  72945. }
  72946. };
  72947. };
  72948. SSAO2RenderingPipeline.prototype._rebuild = function () {
  72949. this._firstUpdate = true;
  72950. _super.prototype._rebuild.call(this);
  72951. };
  72952. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  72953. var numSamples = this.samples;
  72954. var result = [];
  72955. var vector, scale;
  72956. var rand = function (min, max) {
  72957. return Math.random() * (max - min) + min;
  72958. };
  72959. var i = 0;
  72960. while (i < numSamples) {
  72961. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  72962. vector.normalize();
  72963. scale = i / numSamples;
  72964. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  72965. vector.scaleInPlace(scale);
  72966. result.push(vector.x, vector.y, vector.z);
  72967. i++;
  72968. }
  72969. return result;
  72970. };
  72971. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72972. var _this = this;
  72973. var numSamples = this.samples;
  72974. this._sampleSphere = this._generateHemisphere();
  72975. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  72976. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72977. "base", "range", "projection", "near", "far", "texelSize",
  72978. "xViewport", "yViewport", "maxZ", "minZAspect"
  72979. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72980. this._ssaoPostProcess.onApply = function (effect) {
  72981. if (_this._firstUpdate) {
  72982. effect.setArray3("sampleSphere", _this._sampleSphere);
  72983. effect.setFloat("randTextureTiles", 4.0);
  72984. }
  72985. if (!_this._scene.activeCamera) {
  72986. return;
  72987. }
  72988. effect.setFloat("samplesFactor", 1 / _this.samples);
  72989. effect.setFloat("totalStrength", _this.totalStrength);
  72990. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  72991. effect.setFloat("radius", _this.radius);
  72992. effect.setFloat("maxZ", _this.maxZ);
  72993. effect.setFloat("minZAspect", _this.minZAspect);
  72994. effect.setFloat("base", _this.base);
  72995. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72996. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72997. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  72998. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  72999. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73000. effect.setTexture("textureSampler", _this._depthTexture);
  73001. effect.setTexture("normalSampler", _this._normalTexture);
  73002. effect.setTexture("randomSampler", _this._randomTexture);
  73003. };
  73004. };
  73005. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73006. var _this = this;
  73007. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73008. this._ssaoCombinePostProcess.onApply = function (effect) {
  73009. var viewport = _this._scene.activeCamera.viewport;
  73010. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73011. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73012. };
  73013. };
  73014. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73015. var size = 512;
  73016. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73017. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73018. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73019. var context = this._randomTexture.getContext();
  73020. var rand = function (min, max) {
  73021. return Math.random() * (max - min) + min;
  73022. };
  73023. var randVector = BABYLON.Vector3.Zero();
  73024. for (var x = 0; x < size; x++) {
  73025. for (var y = 0; y < size; y++) {
  73026. randVector.x = rand(0.0, 1.0);
  73027. randVector.y = rand(0.0, 1.0);
  73028. randVector.z = 0.0;
  73029. randVector.normalize();
  73030. randVector.scaleInPlace(255);
  73031. randVector.x = Math.floor(randVector.x);
  73032. randVector.y = Math.floor(randVector.y);
  73033. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73034. context.fillRect(x, y, 1, 1);
  73035. }
  73036. }
  73037. this._randomTexture.update(false);
  73038. };
  73039. /**
  73040. * Serialize the rendering pipeline (Used when exporting)
  73041. * @returns the serialized object
  73042. */
  73043. SSAO2RenderingPipeline.prototype.serialize = function () {
  73044. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73045. serializationObject.customType = "SSAO2RenderingPipeline";
  73046. return serializationObject;
  73047. };
  73048. /**
  73049. * Parse the serialized pipeline
  73050. * @param source Source pipeline.
  73051. * @param scene The scene to load the pipeline to.
  73052. * @param rootUrl The URL of the serialized pipeline.
  73053. * @returns An instantiated pipeline from the serialized object.
  73054. */
  73055. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73056. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73057. };
  73058. __decorate([
  73059. BABYLON.serialize()
  73060. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73061. __decorate([
  73062. BABYLON.serialize()
  73063. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73064. __decorate([
  73065. BABYLON.serialize()
  73066. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73067. __decorate([
  73068. BABYLON.serialize("samples")
  73069. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73070. __decorate([
  73071. BABYLON.serialize()
  73072. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73073. __decorate([
  73074. BABYLON.serialize("expensiveBlur")
  73075. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73076. __decorate([
  73077. BABYLON.serialize()
  73078. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73079. __decorate([
  73080. BABYLON.serialize()
  73081. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73082. return SSAO2RenderingPipeline;
  73083. }(BABYLON.PostProcessRenderPipeline));
  73084. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73085. })(BABYLON || (BABYLON = {}));
  73086. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73087. // BABYLON.JS Chromatic Aberration GLSL Shader
  73088. // Author: Olivier Guyot
  73089. // Separates very slightly R, G and B colors on the edges of the screen
  73090. // Inspired by Francois Tarlier & Martins Upitis
  73091. var BABYLON;
  73092. (function (BABYLON) {
  73093. var LensRenderingPipeline = /** @class */ (function (_super) {
  73094. __extends(LensRenderingPipeline, _super);
  73095. /**
  73096. * @constructor
  73097. *
  73098. * Effect parameters are as follow:
  73099. * {
  73100. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73101. * edge_blur: number; // from 0 to x (1 for realism)
  73102. * distortion: number; // from 0 to x (1 for realism)
  73103. * grain_amount: number; // from 0 to 1
  73104. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73105. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73106. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73107. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73108. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73109. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73110. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73111. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73112. * }
  73113. * Note: if an effect parameter is unset, effect is disabled
  73114. *
  73115. * @param {string} name - The rendering pipeline name
  73116. * @param {object} parameters - An object containing all parameters (see above)
  73117. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73118. * @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)
  73119. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73120. */
  73121. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73122. if (ratio === void 0) { ratio = 1.0; }
  73123. var _this = _super.call(this, scene.getEngine(), name) || this;
  73124. // Lens effects can be of the following:
  73125. // - chromatic aberration (slight shift of RGB colors)
  73126. // - blur on the edge of the lens
  73127. // - lens distortion
  73128. // - depth-of-field blur & highlights enhancing
  73129. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73130. // - grain effect (noise or custom texture)
  73131. // Two additional texture samplers are needed:
  73132. // - depth map (for depth-of-field)
  73133. // - grain texture
  73134. /**
  73135. * The chromatic aberration PostProcess id in the pipeline
  73136. */
  73137. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73138. /**
  73139. * The highlights enhancing PostProcess id in the pipeline
  73140. */
  73141. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73142. /**
  73143. * The depth-of-field PostProcess id in the pipeline
  73144. */
  73145. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73146. _this._scene = scene;
  73147. // Fetch texture samplers
  73148. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73149. if (parameters.grain_texture) {
  73150. _this._grainTexture = parameters.grain_texture;
  73151. }
  73152. else {
  73153. _this._createGrainTexture();
  73154. }
  73155. // save parameters
  73156. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73157. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73158. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73159. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73160. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73161. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73162. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73163. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73164. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73165. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73166. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73167. // Create effects
  73168. _this._createChromaticAberrationPostProcess(ratio);
  73169. _this._createHighlightsPostProcess(ratio);
  73170. _this._createDepthOfFieldPostProcess(ratio / 4);
  73171. // Set up pipeline
  73172. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73173. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73174. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73175. if (_this._highlightsGain === -1) {
  73176. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73177. }
  73178. // Finish
  73179. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73180. if (cameras) {
  73181. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73182. }
  73183. return _this;
  73184. }
  73185. // public methods (self explanatory)
  73186. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73187. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73188. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73189. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73190. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73191. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73192. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73193. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73194. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73195. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73196. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73197. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73198. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73199. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73200. };
  73201. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73202. this._highlightsPostProcess.updateEffect();
  73203. };
  73204. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73205. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73206. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73207. this._highlightsGain = amount;
  73208. };
  73209. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73210. if (this._highlightsGain === -1) {
  73211. this._highlightsGain = 1.0;
  73212. }
  73213. this._highlightsThreshold = amount;
  73214. };
  73215. LensRenderingPipeline.prototype.disableHighlights = function () {
  73216. this._highlightsGain = -1;
  73217. };
  73218. /**
  73219. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73220. */
  73221. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73222. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73223. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73224. this._chromaticAberrationPostProcess = null;
  73225. this._highlightsPostProcess = null;
  73226. this._depthOfFieldPostProcess = null;
  73227. this._grainTexture.dispose();
  73228. if (disableDepthRender)
  73229. this._scene.disableDepthRenderer();
  73230. };
  73231. // colors shifting and distortion
  73232. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73233. var _this = this;
  73234. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73235. [], // samplers
  73236. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73237. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73238. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73239. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73240. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73241. effect.setFloat('radialIntensity', 1);
  73242. effect.setFloat2('direction', 17, 17);
  73243. effect.setFloat2('centerPosition', 0.5, 0.5);
  73244. };
  73245. };
  73246. // highlights enhancing
  73247. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73248. var _this = this;
  73249. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73250. [], // samplers
  73251. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73252. this._highlightsPostProcess.onApply = function (effect) {
  73253. effect.setFloat('gain', _this._highlightsGain);
  73254. effect.setFloat('threshold', _this._highlightsThreshold);
  73255. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73256. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73257. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73258. };
  73259. };
  73260. // colors shifting and distortion
  73261. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73262. var _this = this;
  73263. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73264. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73265. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73266. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73267. this._depthOfFieldPostProcess.onApply = function (effect) {
  73268. effect.setTexture("depthSampler", _this._depthTexture);
  73269. effect.setTexture("grainSampler", _this._grainTexture);
  73270. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73271. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73272. effect.setFloat('grain_amount', _this._grainAmount);
  73273. effect.setBool('blur_noise', _this._blurNoise);
  73274. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73275. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73276. effect.setFloat('distortion', _this._distortion);
  73277. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73278. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73279. effect.setFloat('aperture', _this._dofAperture);
  73280. effect.setFloat('darken', _this._dofDarken);
  73281. effect.setFloat('edge_blur', _this._edgeBlur);
  73282. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73283. if (_this._scene.activeCamera) {
  73284. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73285. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73286. }
  73287. };
  73288. };
  73289. // creates a black and white random noise texture, 512x512
  73290. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73291. var size = 512;
  73292. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73293. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73294. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73295. var context = this._grainTexture.getContext();
  73296. var rand = function (min, max) {
  73297. return Math.random() * (max - min) + min;
  73298. };
  73299. var value;
  73300. for (var x = 0; x < size; x++) {
  73301. for (var y = 0; y < size; y++) {
  73302. value = Math.floor(rand(0.42, 0.58) * 255);
  73303. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73304. context.fillRect(x, y, 1, 1);
  73305. }
  73306. }
  73307. this._grainTexture.update(false);
  73308. };
  73309. return LensRenderingPipeline;
  73310. }(BABYLON.PostProcessRenderPipeline));
  73311. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73312. })(BABYLON || (BABYLON = {}));
  73313. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73314. var BABYLON;
  73315. (function (BABYLON) {
  73316. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73317. __extends(StandardRenderingPipeline, _super);
  73318. /**
  73319. * @constructor
  73320. * @param {string} name - The rendering pipeline name
  73321. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73322. * @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)
  73323. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73324. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73325. */
  73326. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73327. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73328. var _this = _super.call(this, scene.getEngine(), name) || this;
  73329. _this.downSampleX4PostProcess = null;
  73330. _this.brightPassPostProcess = null;
  73331. _this.blurHPostProcesses = [];
  73332. _this.blurVPostProcesses = [];
  73333. _this.textureAdderPostProcess = null;
  73334. _this.volumetricLightPostProcess = null;
  73335. _this.volumetricLightSmoothXPostProcess = null;
  73336. _this.volumetricLightSmoothYPostProcess = null;
  73337. _this.volumetricLightMergePostProces = null;
  73338. _this.volumetricLightFinalPostProcess = null;
  73339. _this.luminancePostProcess = null;
  73340. _this.luminanceDownSamplePostProcesses = [];
  73341. _this.hdrPostProcess = null;
  73342. _this.textureAdderFinalPostProcess = null;
  73343. _this.lensFlareFinalPostProcess = null;
  73344. _this.hdrFinalPostProcess = null;
  73345. _this.lensFlarePostProcess = null;
  73346. _this.lensFlareComposePostProcess = null;
  73347. _this.motionBlurPostProcess = null;
  73348. _this.depthOfFieldPostProcess = null;
  73349. // Values
  73350. _this.brightThreshold = 1.0;
  73351. _this.blurWidth = 512.0;
  73352. _this.horizontalBlur = false;
  73353. _this.exposure = 1.0;
  73354. _this.lensTexture = null;
  73355. _this.volumetricLightCoefficient = 0.2;
  73356. _this.volumetricLightPower = 4.0;
  73357. _this.volumetricLightBlurScale = 64.0;
  73358. _this.sourceLight = null;
  73359. _this.hdrMinimumLuminance = 1.0;
  73360. _this.hdrDecreaseRate = 0.5;
  73361. _this.hdrIncreaseRate = 0.5;
  73362. _this.lensColorTexture = null;
  73363. _this.lensFlareStrength = 20.0;
  73364. _this.lensFlareGhostDispersal = 1.4;
  73365. _this.lensFlareHaloWidth = 0.7;
  73366. _this.lensFlareDistortionStrength = 16.0;
  73367. _this.lensStarTexture = null;
  73368. _this.lensFlareDirtTexture = null;
  73369. _this.depthOfFieldDistance = 10.0;
  73370. _this.depthOfFieldBlurWidth = 64.0;
  73371. _this.motionStrength = 1.0;
  73372. // IAnimatable
  73373. _this.animations = [];
  73374. _this._currentDepthOfFieldSource = null;
  73375. _this._hdrCurrentLuminance = 1.0;
  73376. // Getters and setters
  73377. _this._bloomEnabled = true;
  73378. _this._depthOfFieldEnabled = false;
  73379. _this._vlsEnabled = false;
  73380. _this._lensFlareEnabled = false;
  73381. _this._hdrEnabled = false;
  73382. _this._motionBlurEnabled = false;
  73383. _this._motionBlurSamples = 64.0;
  73384. _this._volumetricLightStepsCount = 50.0;
  73385. _this._cameras = cameras || [];
  73386. // Initialize
  73387. _this._scene = scene;
  73388. _this._basePostProcess = originalPostProcess;
  73389. _this._ratio = ratio;
  73390. // Misc
  73391. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73392. // Finish
  73393. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73394. _this._buildPipeline();
  73395. return _this;
  73396. }
  73397. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73398. get: function () {
  73399. return this._bloomEnabled;
  73400. },
  73401. set: function (enabled) {
  73402. if (this._bloomEnabled === enabled) {
  73403. return;
  73404. }
  73405. this._bloomEnabled = enabled;
  73406. this._buildPipeline();
  73407. },
  73408. enumerable: true,
  73409. configurable: true
  73410. });
  73411. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73412. get: function () {
  73413. return this._depthOfFieldEnabled;
  73414. },
  73415. set: function (enabled) {
  73416. if (this._depthOfFieldEnabled === enabled) {
  73417. return;
  73418. }
  73419. this._depthOfFieldEnabled = enabled;
  73420. this._buildPipeline();
  73421. },
  73422. enumerable: true,
  73423. configurable: true
  73424. });
  73425. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73426. get: function () {
  73427. return this._lensFlareEnabled;
  73428. },
  73429. set: function (enabled) {
  73430. if (this._lensFlareEnabled === enabled) {
  73431. return;
  73432. }
  73433. this._lensFlareEnabled = enabled;
  73434. this._buildPipeline();
  73435. },
  73436. enumerable: true,
  73437. configurable: true
  73438. });
  73439. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73440. get: function () {
  73441. return this._hdrEnabled;
  73442. },
  73443. set: function (enabled) {
  73444. if (this._hdrEnabled === enabled) {
  73445. return;
  73446. }
  73447. this._hdrEnabled = enabled;
  73448. this._buildPipeline();
  73449. },
  73450. enumerable: true,
  73451. configurable: true
  73452. });
  73453. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73454. get: function () {
  73455. return this._vlsEnabled;
  73456. },
  73457. set: function (enabled) {
  73458. if (this._vlsEnabled === enabled) {
  73459. return;
  73460. }
  73461. if (enabled) {
  73462. var geometry = this._scene.enableGeometryBufferRenderer();
  73463. if (!geometry) {
  73464. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73465. return;
  73466. }
  73467. }
  73468. this._vlsEnabled = enabled;
  73469. this._buildPipeline();
  73470. },
  73471. enumerable: true,
  73472. configurable: true
  73473. });
  73474. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73475. get: function () {
  73476. return this._motionBlurEnabled;
  73477. },
  73478. set: function (enabled) {
  73479. if (this._motionBlurEnabled === enabled) {
  73480. return;
  73481. }
  73482. this._motionBlurEnabled = enabled;
  73483. this._buildPipeline();
  73484. },
  73485. enumerable: true,
  73486. configurable: true
  73487. });
  73488. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73489. get: function () {
  73490. return this._volumetricLightStepsCount;
  73491. },
  73492. set: function (count) {
  73493. if (this.volumetricLightPostProcess) {
  73494. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73495. }
  73496. this._volumetricLightStepsCount = count;
  73497. },
  73498. enumerable: true,
  73499. configurable: true
  73500. });
  73501. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73502. get: function () {
  73503. return this._motionBlurSamples;
  73504. },
  73505. set: function (samples) {
  73506. if (this.motionBlurPostProcess) {
  73507. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73508. }
  73509. this._motionBlurSamples = samples;
  73510. },
  73511. enumerable: true,
  73512. configurable: true
  73513. });
  73514. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73515. var _this = this;
  73516. var ratio = this._ratio;
  73517. var scene = this._scene;
  73518. this._disposePostProcesses();
  73519. this._reset();
  73520. // Create pass post-process
  73521. if (!this._basePostProcess) {
  73522. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73523. this.originalPostProcess.onApply = function (effect) {
  73524. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73525. };
  73526. }
  73527. else {
  73528. this.originalPostProcess = this._basePostProcess;
  73529. }
  73530. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73531. this._currentDepthOfFieldSource = this.originalPostProcess;
  73532. if (this._bloomEnabled) {
  73533. // Create down sample X4 post-process
  73534. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73535. // Create bright pass post-process
  73536. this._createBrightPassPostProcess(scene, ratio / 2);
  73537. // Create gaussian blur post-processes (down sampling blurs)
  73538. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73539. // Create texture adder post-process
  73540. this._createTextureAdderPostProcess(scene, ratio);
  73541. // Create depth-of-field source post-process
  73542. 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);
  73543. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73544. }
  73545. if (this._vlsEnabled) {
  73546. // Create volumetric light
  73547. this._createVolumetricLightPostProcess(scene, ratio);
  73548. // Create volumetric light final post-process
  73549. 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);
  73550. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73551. }
  73552. if (this._lensFlareEnabled) {
  73553. // Create lens flare post-process
  73554. this._createLensFlarePostProcess(scene, ratio);
  73555. // Create depth-of-field source post-process post lens-flare and disable it now
  73556. 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);
  73557. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73558. }
  73559. if (this._hdrEnabled) {
  73560. // Create luminance
  73561. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73562. // Create HDR
  73563. this._createHdrPostProcess(scene, ratio);
  73564. // Create depth-of-field source post-process post hdr and disable it now
  73565. 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);
  73566. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73567. }
  73568. if (this._depthOfFieldEnabled) {
  73569. // Create gaussian blur used by depth-of-field
  73570. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73571. // Create depth-of-field post-process
  73572. this._createDepthOfFieldPostProcess(scene, ratio);
  73573. }
  73574. if (this._motionBlurEnabled) {
  73575. // Create motion blur post-process
  73576. this._createMotionBlurPostProcess(scene, ratio);
  73577. }
  73578. if (this._cameras !== null) {
  73579. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73580. }
  73581. };
  73582. // Down Sample X4 Post-Processs
  73583. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73584. var _this = this;
  73585. var downSampleX4Offsets = new Array(32);
  73586. 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);
  73587. this.downSampleX4PostProcess.onApply = function (effect) {
  73588. var id = 0;
  73589. var width = _this.downSampleX4PostProcess.width;
  73590. var height = _this.downSampleX4PostProcess.height;
  73591. for (var i = -2; i < 2; i++) {
  73592. for (var j = -2; j < 2; j++) {
  73593. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73594. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73595. id += 2;
  73596. }
  73597. }
  73598. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73599. };
  73600. // Add to pipeline
  73601. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73602. };
  73603. // Brightpass Post-Process
  73604. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73605. var _this = this;
  73606. var brightOffsets = new Array(8);
  73607. 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);
  73608. this.brightPassPostProcess.onApply = function (effect) {
  73609. var sU = (1.0 / _this.brightPassPostProcess.width);
  73610. var sV = (1.0 / _this.brightPassPostProcess.height);
  73611. brightOffsets[0] = -0.5 * sU;
  73612. brightOffsets[1] = 0.5 * sV;
  73613. brightOffsets[2] = 0.5 * sU;
  73614. brightOffsets[3] = 0.5 * sV;
  73615. brightOffsets[4] = -0.5 * sU;
  73616. brightOffsets[5] = -0.5 * sV;
  73617. brightOffsets[6] = 0.5 * sU;
  73618. brightOffsets[7] = -0.5 * sV;
  73619. effect.setArray2("dsOffsets", brightOffsets);
  73620. effect.setFloat("brightThreshold", _this.brightThreshold);
  73621. };
  73622. // Add to pipeline
  73623. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73624. };
  73625. // Create blur H&V post-processes
  73626. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73627. var _this = this;
  73628. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73629. var engine = scene.getEngine();
  73630. 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);
  73631. 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);
  73632. blurX.onActivateObservable.add(function () {
  73633. var dw = blurX.width / engine.getRenderWidth();
  73634. blurX.kernel = _this[blurWidthKey] * dw;
  73635. });
  73636. blurY.onActivateObservable.add(function () {
  73637. var dw = blurY.height / engine.getRenderHeight();
  73638. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73639. });
  73640. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73641. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73642. this.blurHPostProcesses.push(blurX);
  73643. this.blurVPostProcesses.push(blurY);
  73644. };
  73645. // Create texture adder post-process
  73646. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73647. var _this = this;
  73648. 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);
  73649. this.textureAdderPostProcess.onApply = function (effect) {
  73650. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73651. effect.setTexture("lensSampler", _this.lensTexture);
  73652. effect.setFloat("exposure", _this.exposure);
  73653. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73654. };
  73655. // Add to pipeline
  73656. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73657. };
  73658. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73659. var _this = this;
  73660. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73661. geometryRenderer.enablePosition = true;
  73662. var geometry = geometryRenderer.getGBuffer();
  73663. // Base post-process
  73664. 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));
  73665. var depthValues = BABYLON.Vector2.Zero();
  73666. this.volumetricLightPostProcess.onApply = function (effect) {
  73667. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73668. var generator = _this.sourceLight.getShadowGenerator();
  73669. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73670. effect.setTexture("positionSampler", geometry.textures[2]);
  73671. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73672. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73673. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73674. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73675. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73676. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73677. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73678. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73679. effect.setVector2("depthValues", depthValues);
  73680. }
  73681. };
  73682. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73683. // Smooth
  73684. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73685. // Merge
  73686. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73687. this.volumetricLightMergePostProces.onApply = function (effect) {
  73688. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  73689. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73690. };
  73691. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73692. };
  73693. // Create luminance
  73694. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73695. var _this = this;
  73696. // Create luminance
  73697. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73698. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73699. var offsets = [];
  73700. this.luminancePostProcess.onApply = function (effect) {
  73701. var sU = (1.0 / _this.luminancePostProcess.width);
  73702. var sV = (1.0 / _this.luminancePostProcess.height);
  73703. offsets[0] = -0.5 * sU;
  73704. offsets[1] = 0.5 * sV;
  73705. offsets[2] = 0.5 * sU;
  73706. offsets[3] = 0.5 * sV;
  73707. offsets[4] = -0.5 * sU;
  73708. offsets[5] = -0.5 * sV;
  73709. offsets[6] = 0.5 * sU;
  73710. offsets[7] = -0.5 * sV;
  73711. effect.setArray2("lumOffsets", offsets);
  73712. };
  73713. // Add to pipeline
  73714. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73715. // Create down sample luminance
  73716. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73717. var size = Math.pow(3, i);
  73718. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73719. if (i === 0) {
  73720. defines += "#define FINAL_DOWN_SAMPLER";
  73721. }
  73722. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73723. this.luminanceDownSamplePostProcesses.push(postProcess);
  73724. }
  73725. // Create callbacks and add effects
  73726. var lastLuminance = this.luminancePostProcess;
  73727. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73728. var downSampleOffsets = new Array(18);
  73729. pp.onApply = function (effect) {
  73730. if (!lastLuminance) {
  73731. return;
  73732. }
  73733. var id = 0;
  73734. for (var x = -1; x < 2; x++) {
  73735. for (var y = -1; y < 2; y++) {
  73736. downSampleOffsets[id] = x / lastLuminance.width;
  73737. downSampleOffsets[id + 1] = y / lastLuminance.height;
  73738. id += 2;
  73739. }
  73740. }
  73741. effect.setArray2("dsOffsets", downSampleOffsets);
  73742. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  73743. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73744. lastLuminance = _this.luminancePostProcess;
  73745. }
  73746. else {
  73747. lastLuminance = pp;
  73748. }
  73749. };
  73750. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73751. pp.onAfterRender = function (effect) {
  73752. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73753. 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);
  73754. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73755. };
  73756. }
  73757. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  73758. });
  73759. };
  73760. // Create HDR post-process
  73761. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  73762. var _this = this;
  73763. 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);
  73764. var outputLiminance = 1;
  73765. var time = 0;
  73766. var lastTime = 0;
  73767. this.hdrPostProcess.onApply = function (effect) {
  73768. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  73769. time += scene.getEngine().getDeltaTime();
  73770. if (outputLiminance < 0) {
  73771. outputLiminance = _this._hdrCurrentLuminance;
  73772. }
  73773. else {
  73774. var dt = (lastTime - time) / 1000.0;
  73775. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  73776. outputLiminance += _this.hdrDecreaseRate * dt;
  73777. }
  73778. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  73779. outputLiminance -= _this.hdrIncreaseRate * dt;
  73780. }
  73781. else {
  73782. outputLiminance = _this._hdrCurrentLuminance;
  73783. }
  73784. }
  73785. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  73786. effect.setFloat("averageLuminance", outputLiminance);
  73787. lastTime = time;
  73788. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  73789. };
  73790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  73791. };
  73792. // Create lens flare post-process
  73793. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  73794. var _this = this;
  73795. 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);
  73796. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  73797. this._createBlurPostProcesses(scene, ratio / 4, 2);
  73798. 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);
  73799. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  73800. var resolution = new BABYLON.Vector2(0, 0);
  73801. // Lens flare
  73802. this.lensFlarePostProcess.onApply = function (effect) {
  73803. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  73804. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  73805. effect.setFloat("strength", _this.lensFlareStrength);
  73806. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  73807. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  73808. // Shift
  73809. resolution.x = _this.lensFlarePostProcess.width;
  73810. resolution.y = _this.lensFlarePostProcess.height;
  73811. effect.setVector2("resolution", resolution);
  73812. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  73813. };
  73814. // Compose
  73815. 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);
  73816. 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);
  73817. this.lensFlareComposePostProcess.onApply = function (effect) {
  73818. if (!_this._scene.activeCamera) {
  73819. return;
  73820. }
  73821. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73822. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  73823. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  73824. // Lens start rotation matrix
  73825. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  73826. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  73827. 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));
  73828. camRot *= 4.0;
  73829. 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);
  73830. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  73831. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  73832. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  73833. };
  73834. };
  73835. // Create depth-of-field post-process
  73836. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  73837. var _this = this;
  73838. 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);
  73839. this.depthOfFieldPostProcess.onApply = function (effect) {
  73840. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73841. effect.setTexture("depthSampler", _this._getDepthTexture());
  73842. effect.setFloat("distance", _this.depthOfFieldDistance);
  73843. };
  73844. // Add to pipeline
  73845. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  73846. };
  73847. // Create motion blur post-process
  73848. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  73849. var _this = this;
  73850. 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);
  73851. var motionScale = 0;
  73852. var prevViewProjection = BABYLON.Matrix.Identity();
  73853. var invViewProjection = BABYLON.Matrix.Identity();
  73854. var viewProjection = BABYLON.Matrix.Identity();
  73855. var screenSize = BABYLON.Vector2.Zero();
  73856. this.motionBlurPostProcess.onApply = function (effect) {
  73857. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  73858. viewProjection.invertToRef(invViewProjection);
  73859. effect.setMatrix("inverseViewProjection", invViewProjection);
  73860. effect.setMatrix("prevViewProjection", prevViewProjection);
  73861. prevViewProjection = viewProjection;
  73862. screenSize.x = _this.motionBlurPostProcess.width;
  73863. screenSize.y = _this.motionBlurPostProcess.height;
  73864. effect.setVector2("screenSize", screenSize);
  73865. motionScale = scene.getEngine().getFps() / 60.0;
  73866. effect.setFloat("motionScale", motionScale);
  73867. effect.setFloat("motionStrength", _this.motionStrength);
  73868. effect.setTexture("depthSampler", _this._getDepthTexture());
  73869. };
  73870. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  73871. };
  73872. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  73873. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  73874. var renderer = this._scene.enableGeometryBufferRenderer();
  73875. return renderer.getGBuffer().textures[0];
  73876. }
  73877. return this._scene.enableDepthRenderer().getDepthMap();
  73878. };
  73879. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  73880. for (var i = 0; i < this._cameras.length; i++) {
  73881. var camera = this._cameras[i];
  73882. if (this.originalPostProcess) {
  73883. this.originalPostProcess.dispose(camera);
  73884. }
  73885. if (this.downSampleX4PostProcess) {
  73886. this.downSampleX4PostProcess.dispose(camera);
  73887. }
  73888. if (this.brightPassPostProcess) {
  73889. this.brightPassPostProcess.dispose(camera);
  73890. }
  73891. if (this.textureAdderPostProcess) {
  73892. this.textureAdderPostProcess.dispose(camera);
  73893. }
  73894. if (this.textureAdderFinalPostProcess) {
  73895. this.textureAdderFinalPostProcess.dispose(camera);
  73896. }
  73897. if (this.volumetricLightPostProcess) {
  73898. this.volumetricLightPostProcess.dispose(camera);
  73899. }
  73900. if (this.volumetricLightSmoothXPostProcess) {
  73901. this.volumetricLightSmoothXPostProcess.dispose(camera);
  73902. }
  73903. if (this.volumetricLightSmoothYPostProcess) {
  73904. this.volumetricLightSmoothYPostProcess.dispose(camera);
  73905. }
  73906. if (this.volumetricLightMergePostProces) {
  73907. this.volumetricLightMergePostProces.dispose(camera);
  73908. }
  73909. if (this.volumetricLightFinalPostProcess) {
  73910. this.volumetricLightFinalPostProcess.dispose(camera);
  73911. }
  73912. if (this.lensFlarePostProcess) {
  73913. this.lensFlarePostProcess.dispose(camera);
  73914. }
  73915. if (this.lensFlareComposePostProcess) {
  73916. this.lensFlareComposePostProcess.dispose(camera);
  73917. }
  73918. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  73919. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  73920. }
  73921. if (this.luminancePostProcess) {
  73922. this.luminancePostProcess.dispose(camera);
  73923. }
  73924. if (this.hdrPostProcess) {
  73925. this.hdrPostProcess.dispose(camera);
  73926. }
  73927. if (this.hdrFinalPostProcess) {
  73928. this.hdrFinalPostProcess.dispose(camera);
  73929. }
  73930. if (this.depthOfFieldPostProcess) {
  73931. this.depthOfFieldPostProcess.dispose(camera);
  73932. }
  73933. if (this.motionBlurPostProcess) {
  73934. this.motionBlurPostProcess.dispose(camera);
  73935. }
  73936. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  73937. this.blurHPostProcesses[j].dispose(camera);
  73938. }
  73939. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  73940. this.blurVPostProcesses[j].dispose(camera);
  73941. }
  73942. }
  73943. this.originalPostProcess = null;
  73944. this.downSampleX4PostProcess = null;
  73945. this.brightPassPostProcess = null;
  73946. this.textureAdderPostProcess = null;
  73947. this.textureAdderFinalPostProcess = null;
  73948. this.volumetricLightPostProcess = null;
  73949. this.volumetricLightSmoothXPostProcess = null;
  73950. this.volumetricLightSmoothYPostProcess = null;
  73951. this.volumetricLightMergePostProces = null;
  73952. this.volumetricLightFinalPostProcess = null;
  73953. this.lensFlarePostProcess = null;
  73954. this.lensFlareComposePostProcess = null;
  73955. this.luminancePostProcess = null;
  73956. this.hdrPostProcess = null;
  73957. this.hdrFinalPostProcess = null;
  73958. this.depthOfFieldPostProcess = null;
  73959. this.motionBlurPostProcess = null;
  73960. this.luminanceDownSamplePostProcesses = [];
  73961. this.blurHPostProcesses = [];
  73962. this.blurVPostProcesses = [];
  73963. };
  73964. /**
  73965. * Dispose of the pipeline and stop all post processes
  73966. */
  73967. StandardRenderingPipeline.prototype.dispose = function () {
  73968. this._disposePostProcesses();
  73969. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73970. _super.prototype.dispose.call(this);
  73971. };
  73972. /**
  73973. * Serialize the rendering pipeline (Used when exporting)
  73974. * @returns the serialized object
  73975. */
  73976. StandardRenderingPipeline.prototype.serialize = function () {
  73977. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73978. if (this.sourceLight) {
  73979. serializationObject.sourceLightId = this.sourceLight.id;
  73980. }
  73981. serializationObject.customType = "StandardRenderingPipeline";
  73982. return serializationObject;
  73983. };
  73984. /**
  73985. * Parse the serialized pipeline
  73986. * @param source Source pipeline.
  73987. * @param scene The scene to load the pipeline to.
  73988. * @param rootUrl The URL of the serialized pipeline.
  73989. * @returns An instantiated pipeline from the serialized object.
  73990. */
  73991. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73992. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73993. if (source.sourceLightId) {
  73994. p.sourceLight = scene.getLightByID(source.sourceLightId);
  73995. }
  73996. return p;
  73997. };
  73998. // Luminance steps
  73999. StandardRenderingPipeline.LuminanceSteps = 6;
  74000. __decorate([
  74001. BABYLON.serialize()
  74002. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74003. __decorate([
  74004. BABYLON.serialize()
  74005. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74006. __decorate([
  74007. BABYLON.serialize()
  74008. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74009. __decorate([
  74010. BABYLON.serialize()
  74011. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74012. __decorate([
  74013. BABYLON.serializeAsTexture("lensTexture")
  74014. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74015. __decorate([
  74016. BABYLON.serialize()
  74017. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74018. __decorate([
  74019. BABYLON.serialize()
  74020. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74021. __decorate([
  74022. BABYLON.serialize()
  74023. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74024. __decorate([
  74025. BABYLON.serialize()
  74026. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74027. __decorate([
  74028. BABYLON.serialize()
  74029. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74030. __decorate([
  74031. BABYLON.serialize()
  74032. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74033. __decorate([
  74034. BABYLON.serializeAsTexture("lensColorTexture")
  74035. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74036. __decorate([
  74037. BABYLON.serialize()
  74038. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74039. __decorate([
  74040. BABYLON.serialize()
  74041. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74042. __decorate([
  74043. BABYLON.serialize()
  74044. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74045. __decorate([
  74046. BABYLON.serialize()
  74047. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74048. __decorate([
  74049. BABYLON.serializeAsTexture("lensStarTexture")
  74050. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74051. __decorate([
  74052. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74053. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74054. __decorate([
  74055. BABYLON.serialize()
  74056. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74057. __decorate([
  74058. BABYLON.serialize()
  74059. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74060. __decorate([
  74061. BABYLON.serialize()
  74062. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74063. __decorate([
  74064. BABYLON.serialize()
  74065. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74066. __decorate([
  74067. BABYLON.serialize()
  74068. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74069. __decorate([
  74070. BABYLON.serialize()
  74071. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74072. __decorate([
  74073. BABYLON.serialize()
  74074. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74075. __decorate([
  74076. BABYLON.serialize()
  74077. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74078. __decorate([
  74079. BABYLON.serialize()
  74080. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74081. __decorate([
  74082. BABYLON.serialize()
  74083. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74084. __decorate([
  74085. BABYLON.serialize()
  74086. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74087. __decorate([
  74088. BABYLON.serialize()
  74089. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74090. return StandardRenderingPipeline;
  74091. }(BABYLON.PostProcessRenderPipeline));
  74092. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74093. })(BABYLON || (BABYLON = {}));
  74094. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74095. var BABYLON;
  74096. (function (BABYLON) {
  74097. var FxaaPostProcess = /** @class */ (function (_super) {
  74098. __extends(FxaaPostProcess, _super);
  74099. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74100. if (camera === void 0) { camera = null; }
  74101. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74102. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74103. var defines = _this._getDefines();
  74104. _this.updateEffect(defines);
  74105. _this.onApplyObservable.add(function (effect) {
  74106. var texelSize = _this.texelSize;
  74107. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74108. });
  74109. return _this;
  74110. }
  74111. FxaaPostProcess.prototype._getDefines = function () {
  74112. var engine = this.getEngine();
  74113. if (!engine) {
  74114. return null;
  74115. }
  74116. var glInfo = engine.getGlInfo();
  74117. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74118. return "#define MALI 1\n";
  74119. }
  74120. return null;
  74121. };
  74122. return FxaaPostProcess;
  74123. }(BABYLON.PostProcess));
  74124. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74125. })(BABYLON || (BABYLON = {}));
  74126. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74127. var BABYLON;
  74128. (function (BABYLON) {
  74129. /**
  74130. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74131. */
  74132. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74133. __extends(ChromaticAberrationPostProcess, _super);
  74134. /**
  74135. * Creates a new instance ChromaticAberrationPostProcess
  74136. * @param name The name of the effect.
  74137. * @param screenWidth The width of the screen to apply the effect on.
  74138. * @param screenHeight The height of the screen to apply the effect on.
  74139. * @param options The required width/height ratio to downsize to before computing the render pass.
  74140. * @param camera The camera to apply the render pass to.
  74141. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74142. * @param engine The engine which the post process will be applied. (default: current engine)
  74143. * @param reusable If the post process can be reused on the same frame. (default: false)
  74144. * @param textureType Type of textures used when performing the post process. (default: 0)
  74145. * @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)
  74146. */
  74147. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74148. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74149. if (blockCompilation === void 0) { blockCompilation = false; }
  74150. 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;
  74151. /**
  74152. * The amount of seperation of rgb channels (default: 30)
  74153. */
  74154. _this.aberrationAmount = 30;
  74155. /**
  74156. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74157. */
  74158. _this.radialIntensity = 0;
  74159. /**
  74160. * 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))
  74161. */
  74162. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74163. /**
  74164. * 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))
  74165. */
  74166. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74167. _this.onApplyObservable.add(function (effect) {
  74168. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74169. effect.setFloat('screen_width', screenWidth);
  74170. effect.setFloat('screen_height', screenHeight);
  74171. effect.setFloat('radialIntensity', _this.radialIntensity);
  74172. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74173. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74174. });
  74175. return _this;
  74176. }
  74177. return ChromaticAberrationPostProcess;
  74178. }(BABYLON.PostProcess));
  74179. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74180. })(BABYLON || (BABYLON = {}));
  74181. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74182. var BABYLON;
  74183. (function (BABYLON) {
  74184. /**
  74185. * The GrainPostProcess adds noise to the image at mid luminance levels
  74186. */
  74187. var GrainPostProcess = /** @class */ (function (_super) {
  74188. __extends(GrainPostProcess, _super);
  74189. /**
  74190. * Creates a new instance of @see GrainPostProcess
  74191. * @param name The name of the effect.
  74192. * @param options The required width/height ratio to downsize to before computing the render pass.
  74193. * @param camera The camera to apply the render pass to.
  74194. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74195. * @param engine The engine which the post process will be applied. (default: current engine)
  74196. * @param reusable If the post process can be reused on the same frame. (default: false)
  74197. * @param textureType Type of textures used when performing the post process. (default: 0)
  74198. * @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)
  74199. */
  74200. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74201. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74202. if (blockCompilation === void 0) { blockCompilation = false; }
  74203. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74204. /**
  74205. * The intensity of the grain added (default: 30)
  74206. */
  74207. _this.intensity = 30;
  74208. /**
  74209. * If the grain should be randomized on every frame
  74210. */
  74211. _this.animated = false;
  74212. _this.onApplyObservable.add(function (effect) {
  74213. effect.setFloat('intensity', _this.intensity);
  74214. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74215. });
  74216. return _this;
  74217. }
  74218. return GrainPostProcess;
  74219. }(BABYLON.PostProcess));
  74220. BABYLON.GrainPostProcess = GrainPostProcess;
  74221. })(BABYLON || (BABYLON = {}));
  74222. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74223. var BABYLON;
  74224. (function (BABYLON) {
  74225. /**
  74226. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74227. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74228. */
  74229. var SharpenPostProcess = /** @class */ (function (_super) {
  74230. __extends(SharpenPostProcess, _super);
  74231. /**
  74232. * Creates a new instance ConvolutionPostProcess
  74233. * @param name The name of the effect.
  74234. * @param options The required width/height ratio to downsize to before computing the render pass.
  74235. * @param camera The camera to apply the render pass to.
  74236. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74237. * @param engine The engine which the post process will be applied. (default: current engine)
  74238. * @param reusable If the post process can be reused on the same frame. (default: false)
  74239. * @param textureType Type of textures used when performing the post process. (default: 0)
  74240. * @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)
  74241. */
  74242. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74243. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74244. if (blockCompilation === void 0) { blockCompilation = false; }
  74245. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74246. /**
  74247. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74248. */
  74249. _this.colorAmount = 1.0;
  74250. /**
  74251. * How much sharpness should be applied (default: 0.3)
  74252. */
  74253. _this.edgeAmount = 0.3;
  74254. _this.onApply = function (effect) {
  74255. effect.setFloat2("screenSize", _this.width, _this.height);
  74256. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74257. };
  74258. return _this;
  74259. }
  74260. return SharpenPostProcess;
  74261. }(BABYLON.PostProcess));
  74262. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74263. })(BABYLON || (BABYLON = {}));
  74264. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74265. var BABYLON;
  74266. (function (BABYLON) {
  74267. /**
  74268. * The Blur Post Process which blurs an image based on a kernel and direction.
  74269. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74270. */
  74271. var BlurPostProcess = /** @class */ (function (_super) {
  74272. __extends(BlurPostProcess, _super);
  74273. /**
  74274. * Creates a new instance BlurPostProcess
  74275. * @param name The name of the effect.
  74276. * @param direction The direction in which to blur the image.
  74277. * @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.
  74278. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74279. * @param camera The camera to apply the render pass to.
  74280. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74281. * @param engine The engine which the post process will be applied. (default: current engine)
  74282. * @param reusable If the post process can be reused on the same frame. (default: false)
  74283. * @param textureType Type of textures used when performing the post process. (default: 0)
  74284. * @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)
  74285. */
  74286. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74287. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74288. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74289. if (defines === void 0) { defines = ""; }
  74290. if (blockCompilation === void 0) { blockCompilation = false; }
  74291. 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;
  74292. _this.direction = direction;
  74293. _this.blockCompilation = blockCompilation;
  74294. _this._packedFloat = false;
  74295. _this._staticDefines = "";
  74296. _this._staticDefines = defines;
  74297. _this.onApplyObservable.add(function (effect) {
  74298. if (_this._outputTexture) {
  74299. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74300. }
  74301. else {
  74302. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74303. }
  74304. });
  74305. _this.kernel = kernel;
  74306. return _this;
  74307. }
  74308. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74309. /**
  74310. * Gets the length in pixels of the blur sample region
  74311. */
  74312. get: function () {
  74313. return this._idealKernel;
  74314. },
  74315. /**
  74316. * Sets the length in pixels of the blur sample region
  74317. */
  74318. set: function (v) {
  74319. if (this._idealKernel === v) {
  74320. return;
  74321. }
  74322. v = Math.max(v, 1);
  74323. this._idealKernel = v;
  74324. this._kernel = this._nearestBestKernel(v);
  74325. if (!this.blockCompilation) {
  74326. this._updateParameters();
  74327. }
  74328. },
  74329. enumerable: true,
  74330. configurable: true
  74331. });
  74332. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74333. /**
  74334. * Gets wether or not the blur is unpacking/repacking floats
  74335. */
  74336. get: function () {
  74337. return this._packedFloat;
  74338. },
  74339. /**
  74340. * Sets wether or not the blur needs to unpack/repack floats
  74341. */
  74342. set: function (v) {
  74343. if (this._packedFloat === v) {
  74344. return;
  74345. }
  74346. this._packedFloat = v;
  74347. if (!this.blockCompilation) {
  74348. this._updateParameters();
  74349. }
  74350. },
  74351. enumerable: true,
  74352. configurable: true
  74353. });
  74354. /**
  74355. * Updates the effect with the current post process compile time values and recompiles the shader.
  74356. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74357. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74358. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74359. * @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
  74360. * @param onCompiled Called when the shader has been compiled.
  74361. * @param onError Called if there is an error when compiling a shader.
  74362. */
  74363. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74364. if (defines === void 0) { defines = null; }
  74365. if (uniforms === void 0) { uniforms = null; }
  74366. if (samplers === void 0) { samplers = null; }
  74367. this._updateParameters(onCompiled, onError);
  74368. };
  74369. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74370. // Generate sampling offsets and weights
  74371. var N = this._kernel;
  74372. var centerIndex = (N - 1) / 2;
  74373. // Generate Gaussian sampling weights over kernel
  74374. var offsets = [];
  74375. var weights = [];
  74376. var totalWeight = 0;
  74377. for (var i = 0; i < N; i++) {
  74378. var u = i / (N - 1);
  74379. var w = this._gaussianWeight(u * 2.0 - 1);
  74380. offsets[i] = (i - centerIndex);
  74381. weights[i] = w;
  74382. totalWeight += w;
  74383. }
  74384. // Normalize weights
  74385. for (var i = 0; i < weights.length; i++) {
  74386. weights[i] /= totalWeight;
  74387. }
  74388. // Optimize: combine samples to take advantage of hardware linear sampling
  74389. // Walk from left to center, combining pairs (symmetrically)
  74390. var linearSamplingWeights = [];
  74391. var linearSamplingOffsets = [];
  74392. var linearSamplingMap = [];
  74393. for (var i = 0; i <= centerIndex; i += 2) {
  74394. var j = Math.min(i + 1, Math.floor(centerIndex));
  74395. var singleCenterSample = i === j;
  74396. if (singleCenterSample) {
  74397. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74398. }
  74399. else {
  74400. var sharedCell = j === centerIndex;
  74401. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74402. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74403. if (offsetLinear === 0) {
  74404. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74405. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74406. }
  74407. else {
  74408. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74409. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74410. }
  74411. }
  74412. }
  74413. for (var i = 0; i < linearSamplingMap.length; i++) {
  74414. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74415. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74416. }
  74417. // Replace with optimized
  74418. offsets = linearSamplingOffsets;
  74419. weights = linearSamplingWeights;
  74420. // Generate shaders
  74421. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74422. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74423. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74424. var defines = "";
  74425. defines += this._staticDefines;
  74426. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74427. if (this._staticDefines.indexOf("DOF") != -1) {
  74428. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74429. varyingCount--;
  74430. }
  74431. for (var i = 0; i < varyingCount; i++) {
  74432. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74433. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74434. }
  74435. var depCount = 0;
  74436. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74437. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74438. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74439. depCount++;
  74440. }
  74441. if (this.packedFloat) {
  74442. defines += "#define PACKEDFLOAT 1";
  74443. }
  74444. this.blockCompilation = false;
  74445. _super.prototype.updateEffect.call(this, defines, null, null, {
  74446. varyingCount: varyingCount,
  74447. depCount: depCount
  74448. }, onCompiled, onError);
  74449. };
  74450. /**
  74451. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74452. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74453. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74454. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74455. * The gaps between physical kernels are compensated for in the weighting of the samples
  74456. * @param idealKernel Ideal blur kernel.
  74457. * @return Nearest best kernel.
  74458. */
  74459. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74460. var v = Math.round(idealKernel);
  74461. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74462. var k = _a[_i];
  74463. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74464. return Math.max(k, 3);
  74465. }
  74466. }
  74467. return Math.max(v, 3);
  74468. };
  74469. /**
  74470. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74471. * @param x The point on the Gaussian distribution to sample.
  74472. * @return the value of the Gaussian function at x.
  74473. */
  74474. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74475. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74476. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74477. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74478. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74479. // truncated at around 1.3% of peak strength.
  74480. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74481. var sigma = (1 / 3);
  74482. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74483. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74484. var weight = (1.0 / denominator) * Math.exp(exponent);
  74485. return weight;
  74486. };
  74487. /**
  74488. * Generates a string that can be used as a floating point number in GLSL.
  74489. * @param x Value to print.
  74490. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74491. * @return GLSL float string.
  74492. */
  74493. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74494. if (decimalFigures === void 0) { decimalFigures = 8; }
  74495. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74496. };
  74497. return BlurPostProcess;
  74498. }(BABYLON.PostProcess));
  74499. BABYLON.BlurPostProcess = BlurPostProcess;
  74500. })(BABYLON || (BABYLON = {}));
  74501. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74502. var BABYLON;
  74503. (function (BABYLON) {
  74504. /**
  74505. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74506. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74507. * based on samples that have a large difference in distance than the center pixel.
  74508. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74509. */
  74510. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74511. __extends(DepthOfFieldBlurPostProcess, _super);
  74512. /**
  74513. * Creates a new instance CircleOfConfusionPostProcess
  74514. * @param name The name of the effect.
  74515. * @param scene The scene the effect belongs to.
  74516. * @param direction The direction the blur should be applied.
  74517. * @param kernel The size of the kernel used to blur.
  74518. * @param options The required width/height ratio to downsize to before computing the render pass.
  74519. * @param camera The camera to apply the render pass to.
  74520. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74521. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74522. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74523. * @param engine The engine which the post process will be applied. (default: current engine)
  74524. * @param reusable If the post process can be reused on the same frame. (default: false)
  74525. * @param textureType Type of textures used when performing the post process. (default: 0)
  74526. * @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)
  74527. */
  74528. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74529. if (imageToBlur === void 0) { imageToBlur = null; }
  74530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74531. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74532. if (blockCompilation === void 0) { blockCompilation = false; }
  74533. 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;
  74534. _this.direction = direction;
  74535. _this.onApplyObservable.add(function (effect) {
  74536. if (imageToBlur != null) {
  74537. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74538. }
  74539. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74540. if (scene.activeCamera) {
  74541. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74542. }
  74543. });
  74544. return _this;
  74545. }
  74546. return DepthOfFieldBlurPostProcess;
  74547. }(BABYLON.BlurPostProcess));
  74548. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74549. })(BABYLON || (BABYLON = {}));
  74550. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74551. var BABYLON;
  74552. (function (BABYLON) {
  74553. /**
  74554. * Options to be set when merging outputs from the default pipeline.
  74555. */
  74556. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74557. function DepthOfFieldMergePostProcessOptions() {
  74558. }
  74559. return DepthOfFieldMergePostProcessOptions;
  74560. }());
  74561. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74562. /**
  74563. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74564. */
  74565. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74566. __extends(DepthOfFieldMergePostProcess, _super);
  74567. /**
  74568. * Creates a new instance of DepthOfFieldMergePostProcess
  74569. * @param name The name of the effect.
  74570. * @param originalFromInput Post process which's input will be used for the merge.
  74571. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74572. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74573. * @param options The required width/height ratio to downsize to before computing the render pass.
  74574. * @param camera The camera to apply the render pass to.
  74575. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74576. * @param engine The engine which the post process will be applied. (default: current engine)
  74577. * @param reusable If the post process can be reused on the same frame. (default: false)
  74578. * @param textureType Type of textures used when performing the post process. (default: 0)
  74579. * @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)
  74580. */
  74581. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74582. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74583. if (blockCompilation === void 0) { blockCompilation = false; }
  74584. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74585. _this.blurSteps = blurSteps;
  74586. _this.onApplyObservable.add(function (effect) {
  74587. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74588. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74589. blurSteps.forEach(function (step, index) {
  74590. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74591. });
  74592. });
  74593. if (!blockCompilation) {
  74594. _this.updateEffect();
  74595. }
  74596. return _this;
  74597. }
  74598. /**
  74599. * Updates the effect with the current post process compile time values and recompiles the shader.
  74600. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74601. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74602. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74603. * @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
  74604. * @param onCompiled Called when the shader has been compiled.
  74605. * @param onError Called if there is an error when compiling a shader.
  74606. */
  74607. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74608. if (defines === void 0) { defines = null; }
  74609. if (uniforms === void 0) { uniforms = null; }
  74610. if (samplers === void 0) { samplers = null; }
  74611. if (!defines) {
  74612. defines = "";
  74613. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74614. }
  74615. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74616. };
  74617. return DepthOfFieldMergePostProcess;
  74618. }(BABYLON.PostProcess));
  74619. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74620. })(BABYLON || (BABYLON = {}));
  74621. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74622. var BABYLON;
  74623. (function (BABYLON) {
  74624. /**
  74625. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74626. */
  74627. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74628. __extends(CircleOfConfusionPostProcess, _super);
  74629. /**
  74630. * Creates a new instance CircleOfConfusionPostProcess
  74631. * @param name The name of the effect.
  74632. * @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.
  74633. * @param options The required width/height ratio to downsize to before computing the render pass.
  74634. * @param camera The camera to apply the render pass to.
  74635. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74636. * @param engine The engine which the post process will be applied. (default: current engine)
  74637. * @param reusable If the post process can be reused on the same frame. (default: false)
  74638. * @param textureType Type of textures used when performing the post process. (default: 0)
  74639. * @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)
  74640. */
  74641. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74642. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74643. if (blockCompilation === void 0) { blockCompilation = false; }
  74644. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74645. /**
  74646. * 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.
  74647. */
  74648. _this.lensSize = 50;
  74649. /**
  74650. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74651. */
  74652. _this.fStop = 1.4;
  74653. /**
  74654. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74655. */
  74656. _this.focusDistance = 2000;
  74657. /**
  74658. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74659. */
  74660. _this.focalLength = 50;
  74661. _this._depthTexture = null;
  74662. _this._depthTexture = depthTexture;
  74663. _this.onApplyObservable.add(function (effect) {
  74664. if (!_this._depthTexture) {
  74665. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74666. return;
  74667. }
  74668. effect.setTexture("depthSampler", _this._depthTexture);
  74669. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74670. var aperture = _this.lensSize / _this.fStop;
  74671. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74672. effect.setFloat('focusDistance', _this.focusDistance);
  74673. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74674. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74675. });
  74676. return _this;
  74677. }
  74678. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74679. /**
  74680. * 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.
  74681. */
  74682. set: function (value) {
  74683. this._depthTexture = value;
  74684. },
  74685. enumerable: true,
  74686. configurable: true
  74687. });
  74688. return CircleOfConfusionPostProcess;
  74689. }(BABYLON.PostProcess));
  74690. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74691. })(BABYLON || (BABYLON = {}));
  74692. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74693. var BABYLON;
  74694. (function (BABYLON) {
  74695. /**
  74696. * Specifies the level of max blur that should be applied when using the depth of field effect
  74697. */
  74698. var DepthOfFieldEffectBlurLevel;
  74699. (function (DepthOfFieldEffectBlurLevel) {
  74700. /**
  74701. * Subtle blur
  74702. */
  74703. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74704. /**
  74705. * Medium blur
  74706. */
  74707. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74708. /**
  74709. * Large blur
  74710. */
  74711. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74712. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74713. ;
  74714. /**
  74715. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74716. */
  74717. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74718. __extends(DepthOfFieldEffect, _super);
  74719. /**
  74720. * Creates a new instance DepthOfFieldEffect
  74721. * @param scene The scene the effect belongs to.
  74722. * @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.
  74723. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74724. * @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)
  74725. */
  74726. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74727. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74728. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74729. if (blockCompilation === void 0) { blockCompilation = false; }
  74730. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74731. return _this._effects;
  74732. }, true) || this;
  74733. /**
  74734. * Internal post processes in depth of field effect
  74735. */
  74736. _this._effects = [];
  74737. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74738. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74739. // 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)
  74740. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74741. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74742. _this._depthOfFieldBlurY = [];
  74743. _this._depthOfFieldBlurX = [];
  74744. var blurCount = 1;
  74745. var kernelSize = 15;
  74746. switch (blurLevel) {
  74747. case DepthOfFieldEffectBlurLevel.High: {
  74748. blurCount = 3;
  74749. kernelSize = 51;
  74750. break;
  74751. }
  74752. case DepthOfFieldEffectBlurLevel.Medium: {
  74753. blurCount = 2;
  74754. kernelSize = 31;
  74755. break;
  74756. }
  74757. default: {
  74758. kernelSize = 15;
  74759. blurCount = 1;
  74760. break;
  74761. }
  74762. }
  74763. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  74764. var ratio = 1.0;
  74765. for (var i = 0; i < blurCount; i++) {
  74766. 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);
  74767. blurY.autoClear = false;
  74768. ratio = 0.75 / Math.pow(2, i);
  74769. 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);
  74770. blurX.autoClear = false;
  74771. _this._depthOfFieldBlurY.push(blurY);
  74772. _this._depthOfFieldBlurX.push(blurX);
  74773. }
  74774. // Set all post processes on the effect.
  74775. _this._effects = [_this._circleOfConfusion];
  74776. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74777. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74778. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74779. }
  74780. // Merge blurred images with original image based on circleOfConfusion
  74781. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74782. _this._dofMerge.autoClear = false;
  74783. _this._effects.push(_this._dofMerge);
  74784. return _this;
  74785. }
  74786. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  74787. get: function () {
  74788. return this._circleOfConfusion.focalLength;
  74789. },
  74790. /**
  74791. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  74792. */
  74793. set: function (value) {
  74794. this._circleOfConfusion.focalLength = value;
  74795. },
  74796. enumerable: true,
  74797. configurable: true
  74798. });
  74799. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  74800. get: function () {
  74801. return this._circleOfConfusion.fStop;
  74802. },
  74803. /**
  74804. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74805. */
  74806. set: function (value) {
  74807. this._circleOfConfusion.fStop = value;
  74808. },
  74809. enumerable: true,
  74810. configurable: true
  74811. });
  74812. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  74813. get: function () {
  74814. return this._circleOfConfusion.focusDistance;
  74815. },
  74816. /**
  74817. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74818. */
  74819. set: function (value) {
  74820. this._circleOfConfusion.focusDistance = value;
  74821. },
  74822. enumerable: true,
  74823. configurable: true
  74824. });
  74825. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  74826. get: function () {
  74827. return this._circleOfConfusion.lensSize;
  74828. },
  74829. /**
  74830. * 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.
  74831. */
  74832. set: function (value) {
  74833. this._circleOfConfusion.lensSize = value;
  74834. },
  74835. enumerable: true,
  74836. configurable: true
  74837. });
  74838. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  74839. /**
  74840. * 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.
  74841. */
  74842. set: function (value) {
  74843. this._circleOfConfusion.depthTexture = value;
  74844. },
  74845. enumerable: true,
  74846. configurable: true
  74847. });
  74848. /**
  74849. * Disposes each of the internal effects for a given camera.
  74850. * @param camera The camera to dispose the effect on.
  74851. */
  74852. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  74853. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74854. this._effects[effectIndex].dispose(camera);
  74855. }
  74856. };
  74857. /**
  74858. * Internal
  74859. */
  74860. DepthOfFieldEffect.prototype._updateEffects = function () {
  74861. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74862. this._effects[effectIndex].updateEffect();
  74863. }
  74864. };
  74865. /**
  74866. * Internal
  74867. * @returns if all the contained post processes are ready.
  74868. */
  74869. DepthOfFieldEffect.prototype._isReady = function () {
  74870. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74871. if (!this._effects[effectIndex].isReady()) {
  74872. return false;
  74873. }
  74874. }
  74875. return true;
  74876. };
  74877. return DepthOfFieldEffect;
  74878. }(BABYLON.PostProcessRenderEffect));
  74879. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  74880. })(BABYLON || (BABYLON = {}));
  74881. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  74882. var BABYLON;
  74883. (function (BABYLON) {
  74884. /**
  74885. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74886. */
  74887. var BloomMergePostProcess = /** @class */ (function (_super) {
  74888. __extends(BloomMergePostProcess, _super);
  74889. /**
  74890. * Creates a new instance of @see BloomMergePostProcess
  74891. * @param name The name of the effect.
  74892. * @param originalFromInput Post process which's input will be used for the merge.
  74893. * @param blurred Blurred highlights post process which's output will be used.
  74894. * @param weight Weight of the bloom to be added to the original input.
  74895. * @param options The required width/height ratio to downsize to before computing the render pass.
  74896. * @param camera The camera to apply the render pass to.
  74897. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74898. * @param engine The engine which the post process will be applied. (default: current engine)
  74899. * @param reusable If the post process can be reused on the same frame. (default: false)
  74900. * @param textureType Type of textures used when performing the post process. (default: 0)
  74901. * @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)
  74902. */
  74903. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74904. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74905. if (blockCompilation === void 0) { blockCompilation = false; }
  74906. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74907. _this.weight = weight;
  74908. _this.onApplyObservable.add(function (effect) {
  74909. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74910. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  74911. effect.setFloat("bloomWeight", _this.weight);
  74912. });
  74913. if (!blockCompilation) {
  74914. _this.updateEffect();
  74915. }
  74916. return _this;
  74917. }
  74918. return BloomMergePostProcess;
  74919. }(BABYLON.PostProcess));
  74920. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  74921. })(BABYLON || (BABYLON = {}));
  74922. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  74923. var BABYLON;
  74924. (function (BABYLON) {
  74925. /**
  74926. * 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.
  74927. */
  74928. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  74929. __extends(ExtractHighlightsPostProcess, _super);
  74930. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74931. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74932. if (blockCompilation === void 0) { blockCompilation = false; }
  74933. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74934. /**
  74935. * The luminance threshold, pixels below this value will be set to black.
  74936. */
  74937. _this.threshold = 0.9;
  74938. /**
  74939. * Internal
  74940. */
  74941. _this._exposure = 1;
  74942. /**
  74943. * Post process which has the input texture to be used when performing highlight extraction
  74944. */
  74945. _this._inputPostProcess = null;
  74946. _this.onApplyObservable.add(function (effect) {
  74947. if (_this._inputPostProcess) {
  74948. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  74949. }
  74950. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  74951. effect.setFloat('exposure', _this._exposure);
  74952. });
  74953. return _this;
  74954. }
  74955. return ExtractHighlightsPostProcess;
  74956. }(BABYLON.PostProcess));
  74957. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  74958. })(BABYLON || (BABYLON = {}));
  74959. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  74960. var BABYLON;
  74961. (function (BABYLON) {
  74962. /**
  74963. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  74964. */
  74965. var BloomEffect = /** @class */ (function (_super) {
  74966. __extends(BloomEffect, _super);
  74967. /**
  74968. * Creates a new instance of @see BloomEffect
  74969. * @param scene The scene the effect belongs to.
  74970. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  74971. * @param bloomKernel The size of the kernel to be used when applying the blur.
  74972. * @param bloomWeight The the strength of bloom.
  74973. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74974. * @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)
  74975. */
  74976. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  74977. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74978. if (blockCompilation === void 0) { blockCompilation = false; }
  74979. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  74980. return _this._effects;
  74981. }, true) || this;
  74982. _this.bloomScale = bloomScale;
  74983. /**
  74984. * Internal
  74985. */
  74986. _this._effects = [];
  74987. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74988. _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);
  74989. _this._blurX.alwaysForcePOT = true;
  74990. _this._blurX.autoClear = false;
  74991. _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);
  74992. _this._blurY.alwaysForcePOT = true;
  74993. _this._blurY.autoClear = false;
  74994. _this.kernel = bloomKernel;
  74995. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  74996. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74997. _this._merge.autoClear = false;
  74998. _this._effects.push(_this._merge);
  74999. return _this;
  75000. }
  75001. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75002. /**
  75003. * The luminance threshold to find bright areas of the image to bloom.
  75004. */
  75005. get: function () {
  75006. return this._downscale.threshold;
  75007. },
  75008. set: function (value) {
  75009. this._downscale.threshold = value;
  75010. },
  75011. enumerable: true,
  75012. configurable: true
  75013. });
  75014. Object.defineProperty(BloomEffect.prototype, "weight", {
  75015. /**
  75016. * The strength of the bloom.
  75017. */
  75018. get: function () {
  75019. return this._merge.weight;
  75020. },
  75021. set: function (value) {
  75022. this._merge.weight = value;
  75023. },
  75024. enumerable: true,
  75025. configurable: true
  75026. });
  75027. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75028. /**
  75029. * Specifies the size of the bloom blur kernel, relative to the final output size
  75030. */
  75031. get: function () {
  75032. return this._blurX.kernel / this.bloomScale;
  75033. },
  75034. set: function (value) {
  75035. this._blurX.kernel = value * this.bloomScale;
  75036. this._blurY.kernel = value * this.bloomScale;
  75037. },
  75038. enumerable: true,
  75039. configurable: true
  75040. });
  75041. /**
  75042. * Disposes each of the internal effects for a given camera.
  75043. * @param camera The camera to dispose the effect on.
  75044. */
  75045. BloomEffect.prototype.disposeEffects = function (camera) {
  75046. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75047. this._effects[effectIndex].dispose(camera);
  75048. }
  75049. };
  75050. /**
  75051. * Internal
  75052. */
  75053. BloomEffect.prototype._updateEffects = function () {
  75054. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75055. this._effects[effectIndex].updateEffect();
  75056. }
  75057. };
  75058. /**
  75059. * Internal
  75060. * @returns if all the contained post processes are ready.
  75061. */
  75062. BloomEffect.prototype._isReady = function () {
  75063. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75064. if (!this._effects[effectIndex].isReady()) {
  75065. return false;
  75066. }
  75067. }
  75068. return true;
  75069. };
  75070. return BloomEffect;
  75071. }(BABYLON.PostProcessRenderEffect));
  75072. BABYLON.BloomEffect = BloomEffect;
  75073. })(BABYLON || (BABYLON = {}));
  75074. //# sourceMappingURL=babylon.bloomEffect.js.map
  75075. var BABYLON;
  75076. (function (BABYLON) {
  75077. /**
  75078. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75079. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75080. */
  75081. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75082. __extends(DefaultRenderingPipeline, _super);
  75083. /**
  75084. * @constructor
  75085. * @param {string} name - The rendering pipeline name (default: "")
  75086. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75087. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75088. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75089. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75090. */
  75091. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75092. if (name === void 0) { name = ""; }
  75093. if (hdr === void 0) { hdr = true; }
  75094. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75095. if (automaticBuild === void 0) { automaticBuild = true; }
  75096. var _this = _super.call(this, scene.getEngine(), name) || this;
  75097. _this._originalCameras = [];
  75098. /**
  75099. * ID of the sharpen post process,
  75100. */
  75101. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75102. /**
  75103. * ID of the image processing post process;
  75104. */
  75105. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75106. /**
  75107. * ID of the Fast Approximate Anti-Aliasing post process;
  75108. */
  75109. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75110. /**
  75111. * ID of the chromatic aberration post process,
  75112. */
  75113. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75114. /**
  75115. * ID of the grain post process
  75116. */
  75117. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75118. /**
  75119. * Glow post process which adds a glow to emmisive areas of the image
  75120. */
  75121. _this._glowLayer = null;
  75122. /**
  75123. * Animations which can be used to tweak settings over a period of time
  75124. */
  75125. _this.animations = [];
  75126. _this._imageProcessingConfigurationObserver = null;
  75127. // Values
  75128. _this._sharpenEnabled = false;
  75129. _this._bloomEnabled = false;
  75130. _this._depthOfFieldEnabled = false;
  75131. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75132. _this._fxaaEnabled = false;
  75133. _this._imageProcessingEnabled = true;
  75134. _this._bloomScale = 0.5;
  75135. _this._chromaticAberrationEnabled = false;
  75136. _this._grainEnabled = false;
  75137. _this._buildAllowed = true;
  75138. _this._resizeObserver = null;
  75139. _this._hardwareScaleLevel = 1.0;
  75140. _this._bloomKernel = 64;
  75141. /**
  75142. * Specifies the weight of the bloom in the final rendering
  75143. */
  75144. _this._bloomWeight = 0.15;
  75145. /**
  75146. * Specifies the luma threshold for the area that will be blurred by the bloom
  75147. */
  75148. _this._bloomThreshold = 0.9;
  75149. _this._samples = 1;
  75150. _this._hasCleared = false;
  75151. _this._prevPostProcess = null;
  75152. _this._prevPrevPostProcess = null;
  75153. _this._cameras = cameras || scene.cameras;
  75154. _this._originalCameras = _this._cameras.slice();
  75155. _this._buildAllowed = automaticBuild;
  75156. // Initialize
  75157. _this._scene = scene;
  75158. var caps = _this._scene.getEngine().getCaps();
  75159. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75160. // Misc
  75161. if (_this._hdr) {
  75162. if (caps.textureHalfFloatRender) {
  75163. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75164. }
  75165. else if (caps.textureFloatRender) {
  75166. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75167. }
  75168. }
  75169. else {
  75170. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75171. }
  75172. // Attach
  75173. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75174. var engine = _this._scene.getEngine();
  75175. // Create post processes before hand so they can be modified before enabled.
  75176. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75177. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75178. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75179. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75180. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75181. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75182. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75183. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75184. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75185. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75186. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75187. _this.bloomKernel = _this.bloomKernel;
  75188. });
  75189. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75190. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75191. });
  75192. _this._buildPipeline();
  75193. return _this;
  75194. }
  75195. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75196. get: function () {
  75197. return this._sharpenEnabled;
  75198. },
  75199. /**
  75200. * Enable or disable the sharpen process from the pipeline
  75201. */
  75202. set: function (enabled) {
  75203. if (this._sharpenEnabled === enabled) {
  75204. return;
  75205. }
  75206. this._sharpenEnabled = enabled;
  75207. this._buildPipeline();
  75208. },
  75209. enumerable: true,
  75210. configurable: true
  75211. });
  75212. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75213. /**
  75214. * Specifies the size of the bloom blur kernel, relative to the final output size
  75215. */
  75216. get: function () {
  75217. return this._bloomKernel;
  75218. },
  75219. set: function (value) {
  75220. this._bloomKernel = value;
  75221. this.bloom.kernel = value / this._hardwareScaleLevel;
  75222. },
  75223. enumerable: true,
  75224. configurable: true
  75225. });
  75226. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75227. get: function () {
  75228. return this._bloomWeight;
  75229. },
  75230. /**
  75231. * The strength of the bloom.
  75232. */
  75233. set: function (value) {
  75234. if (this._bloomWeight === value) {
  75235. return;
  75236. }
  75237. this.bloom.weight = value;
  75238. this._bloomWeight = value;
  75239. },
  75240. enumerable: true,
  75241. configurable: true
  75242. });
  75243. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75244. get: function () {
  75245. return this._bloomThreshold;
  75246. },
  75247. /**
  75248. * The strength of the bloom.
  75249. */
  75250. set: function (value) {
  75251. if (this._bloomThreshold === value) {
  75252. return;
  75253. }
  75254. this.bloom.threshold = value;
  75255. this._bloomThreshold = value;
  75256. },
  75257. enumerable: true,
  75258. configurable: true
  75259. });
  75260. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75261. get: function () {
  75262. return this._bloomScale;
  75263. },
  75264. /**
  75265. * The scale of the bloom, lower value will provide better performance.
  75266. */
  75267. set: function (value) {
  75268. if (this._bloomScale === value) {
  75269. return;
  75270. }
  75271. this._bloomScale = value;
  75272. // recreate bloom and dispose old as this setting is not dynamic
  75273. this._rebuildBloom();
  75274. this._buildPipeline();
  75275. },
  75276. enumerable: true,
  75277. configurable: true
  75278. });
  75279. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75280. get: function () {
  75281. return this._bloomEnabled;
  75282. },
  75283. /**
  75284. * Enable or disable the bloom from the pipeline
  75285. */
  75286. set: function (enabled) {
  75287. if (this._bloomEnabled === enabled) {
  75288. return;
  75289. }
  75290. this._bloomEnabled = enabled;
  75291. this._buildPipeline();
  75292. },
  75293. enumerable: true,
  75294. configurable: true
  75295. });
  75296. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75297. // recreate bloom and dispose old as this setting is not dynamic
  75298. var oldBloom = this.bloom;
  75299. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75300. this.bloom.threshold = oldBloom.threshold;
  75301. for (var i = 0; i < this._cameras.length; i++) {
  75302. oldBloom.disposeEffects(this._cameras[i]);
  75303. }
  75304. };
  75305. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75306. /**
  75307. * If the depth of field is enabled.
  75308. */
  75309. get: function () {
  75310. return this._depthOfFieldEnabled;
  75311. },
  75312. set: function (enabled) {
  75313. if (this._depthOfFieldEnabled === enabled) {
  75314. return;
  75315. }
  75316. this._depthOfFieldEnabled = enabled;
  75317. this._buildPipeline();
  75318. },
  75319. enumerable: true,
  75320. configurable: true
  75321. });
  75322. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75323. /**
  75324. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75325. */
  75326. get: function () {
  75327. return this._depthOfFieldBlurLevel;
  75328. },
  75329. set: function (value) {
  75330. if (this._depthOfFieldBlurLevel === value) {
  75331. return;
  75332. }
  75333. this._depthOfFieldBlurLevel = value;
  75334. // recreate dof and dispose old as this setting is not dynamic
  75335. var oldDof = this.depthOfField;
  75336. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75337. this.depthOfField.focalLength = oldDof.focalLength;
  75338. this.depthOfField.focusDistance = oldDof.focusDistance;
  75339. this.depthOfField.fStop = oldDof.fStop;
  75340. this.depthOfField.lensSize = oldDof.lensSize;
  75341. for (var i = 0; i < this._cameras.length; i++) {
  75342. oldDof.disposeEffects(this._cameras[i]);
  75343. }
  75344. this._buildPipeline();
  75345. },
  75346. enumerable: true,
  75347. configurable: true
  75348. });
  75349. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75350. get: function () {
  75351. return this._fxaaEnabled;
  75352. },
  75353. /**
  75354. * If the anti aliasing is enabled.
  75355. */
  75356. set: function (enabled) {
  75357. if (this._fxaaEnabled === enabled) {
  75358. return;
  75359. }
  75360. this._fxaaEnabled = enabled;
  75361. this._buildPipeline();
  75362. },
  75363. enumerable: true,
  75364. configurable: true
  75365. });
  75366. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75367. get: function () {
  75368. return this._samples;
  75369. },
  75370. /**
  75371. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75372. */
  75373. set: function (sampleCount) {
  75374. if (this._samples === sampleCount) {
  75375. return;
  75376. }
  75377. this._samples = sampleCount;
  75378. this._buildPipeline();
  75379. },
  75380. enumerable: true,
  75381. configurable: true
  75382. });
  75383. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75384. get: function () {
  75385. return this._imageProcessingEnabled;
  75386. },
  75387. /**
  75388. * If image processing is enabled.
  75389. */
  75390. set: function (enabled) {
  75391. if (this._imageProcessingEnabled === enabled) {
  75392. return;
  75393. }
  75394. this._imageProcessingEnabled = enabled;
  75395. this._buildPipeline();
  75396. },
  75397. enumerable: true,
  75398. configurable: true
  75399. });
  75400. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  75401. get: function () {
  75402. return this._glowLayer == null;
  75403. },
  75404. /**
  75405. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  75406. */
  75407. set: function (enabled) {
  75408. if (enabled && !this._glowLayer) {
  75409. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  75410. }
  75411. else if (!enabled && this._glowLayer) {
  75412. this._glowLayer.dispose();
  75413. this._glowLayer = null;
  75414. }
  75415. },
  75416. enumerable: true,
  75417. configurable: true
  75418. });
  75419. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75420. get: function () {
  75421. return this._chromaticAberrationEnabled;
  75422. },
  75423. /**
  75424. * Enable or disable the chromaticAberration process from the pipeline
  75425. */
  75426. set: function (enabled) {
  75427. if (this._chromaticAberrationEnabled === enabled) {
  75428. return;
  75429. }
  75430. this._chromaticAberrationEnabled = enabled;
  75431. this._buildPipeline();
  75432. },
  75433. enumerable: true,
  75434. configurable: true
  75435. });
  75436. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75437. get: function () {
  75438. return this._grainEnabled;
  75439. },
  75440. /**
  75441. * Enable or disable the grain process from the pipeline
  75442. */
  75443. set: function (enabled) {
  75444. if (this._grainEnabled === enabled) {
  75445. return;
  75446. }
  75447. this._grainEnabled = enabled;
  75448. this._buildPipeline();
  75449. },
  75450. enumerable: true,
  75451. configurable: true
  75452. });
  75453. /**
  75454. * Force the compilation of the entire pipeline.
  75455. */
  75456. DefaultRenderingPipeline.prototype.prepare = function () {
  75457. var previousState = this._buildAllowed;
  75458. this._buildAllowed = true;
  75459. this._buildPipeline();
  75460. this._buildAllowed = previousState;
  75461. };
  75462. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75463. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75464. if (this._hasCleared) {
  75465. postProcess.autoClear = false;
  75466. }
  75467. else {
  75468. postProcess.autoClear = true;
  75469. this._scene.autoClear = false;
  75470. this._hasCleared = true;
  75471. }
  75472. if (!skipTextureSharing) {
  75473. if (this._prevPrevPostProcess) {
  75474. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75475. }
  75476. else {
  75477. postProcess.useOwnOutput();
  75478. }
  75479. if (this._prevPostProcess) {
  75480. this._prevPrevPostProcess = this._prevPostProcess;
  75481. }
  75482. this._prevPostProcess = postProcess;
  75483. }
  75484. };
  75485. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75486. var _this = this;
  75487. if (!this._buildAllowed) {
  75488. return;
  75489. }
  75490. this._scene.autoClear = true;
  75491. var engine = this._scene.getEngine();
  75492. this._disposePostProcesses();
  75493. if (this._cameras !== null) {
  75494. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75495. // get back cameras to be used to reattach pipeline
  75496. this._cameras = this._originalCameras.slice();
  75497. }
  75498. this._reset();
  75499. this._prevPostProcess = null;
  75500. this._prevPrevPostProcess = null;
  75501. this._hasCleared = false;
  75502. if (this.depthOfFieldEnabled) {
  75503. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75504. this.depthOfField.depthTexture = depthTexture;
  75505. if (!this.depthOfField._isReady()) {
  75506. this.depthOfField._updateEffects();
  75507. }
  75508. this.addEffect(this.depthOfField);
  75509. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75510. }
  75511. if (this.bloomEnabled) {
  75512. if (!this.bloom._isReady()) {
  75513. this.bloom._updateEffects();
  75514. }
  75515. this.addEffect(this.bloom);
  75516. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75517. }
  75518. if (this._imageProcessingEnabled) {
  75519. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75520. if (this._hdr) {
  75521. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75522. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75523. }
  75524. else {
  75525. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75526. }
  75527. }
  75528. if (this.sharpenEnabled) {
  75529. if (!this.sharpen.isReady()) {
  75530. this.sharpen.updateEffect();
  75531. }
  75532. this.addEffect(this._sharpenEffect);
  75533. this._setAutoClearAndTextureSharing(this.sharpen);
  75534. }
  75535. if (this.grainEnabled) {
  75536. if (!this.grain.isReady()) {
  75537. this.grain.updateEffect();
  75538. }
  75539. this.addEffect(this._grainEffect);
  75540. this._setAutoClearAndTextureSharing(this.grain);
  75541. }
  75542. if (this.chromaticAberrationEnabled) {
  75543. if (!this.chromaticAberration.isReady()) {
  75544. this.chromaticAberration.updateEffect();
  75545. }
  75546. this.addEffect(this._chromaticAberrationEffect);
  75547. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75548. }
  75549. if (this.fxaaEnabled) {
  75550. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75551. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75552. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75553. }
  75554. if (this._cameras !== null) {
  75555. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75556. }
  75557. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75558. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75559. }
  75560. };
  75561. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75562. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75563. for (var i = 0; i < this._cameras.length; i++) {
  75564. var camera = this._cameras[i];
  75565. if (this.imageProcessing) {
  75566. this.imageProcessing.dispose(camera);
  75567. }
  75568. if (this.fxaa) {
  75569. this.fxaa.dispose(camera);
  75570. }
  75571. // These are created in the constructor and should not be disposed on every pipeline change
  75572. if (disposeNonRecreated) {
  75573. if (this.sharpen) {
  75574. this.sharpen.dispose(camera);
  75575. }
  75576. if (this.depthOfField) {
  75577. this.depthOfField.disposeEffects(camera);
  75578. }
  75579. if (this.bloom) {
  75580. this.bloom.disposeEffects(camera);
  75581. }
  75582. if (this.chromaticAberration) {
  75583. this.chromaticAberration.dispose(camera);
  75584. }
  75585. if (this.grain) {
  75586. this.grain.dispose(camera);
  75587. }
  75588. if (this._glowLayer) {
  75589. this._glowLayer.dispose();
  75590. }
  75591. }
  75592. }
  75593. this.imageProcessing = null;
  75594. this.fxaa = null;
  75595. if (disposeNonRecreated) {
  75596. this.sharpen = null;
  75597. this._sharpenEffect = null;
  75598. this.depthOfField = null;
  75599. this.bloom = null;
  75600. this.chromaticAberration = null;
  75601. this._chromaticAberrationEffect = null;
  75602. this.grain = null;
  75603. this._grainEffect = null;
  75604. this._glowLayer = null;
  75605. }
  75606. };
  75607. /**
  75608. * Dispose of the pipeline and stop all post processes
  75609. */
  75610. DefaultRenderingPipeline.prototype.dispose = function () {
  75611. this._disposePostProcesses(true);
  75612. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75613. this._scene.autoClear = true;
  75614. if (this._resizeObserver) {
  75615. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75616. this._resizeObserver = null;
  75617. }
  75618. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75619. _super.prototype.dispose.call(this);
  75620. };
  75621. /**
  75622. * Serialize the rendering pipeline (Used when exporting)
  75623. * @returns the serialized object
  75624. */
  75625. DefaultRenderingPipeline.prototype.serialize = function () {
  75626. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75627. serializationObject.customType = "DefaultRenderingPipeline";
  75628. return serializationObject;
  75629. };
  75630. /**
  75631. * Parse the serialized pipeline
  75632. * @param source Source pipeline.
  75633. * @param scene The scene to load the pipeline to.
  75634. * @param rootUrl The URL of the serialized pipeline.
  75635. * @returns An instantiated pipeline from the serialized object.
  75636. */
  75637. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75638. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75639. };
  75640. __decorate([
  75641. BABYLON.serialize()
  75642. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75643. __decorate([
  75644. BABYLON.serialize()
  75645. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75646. __decorate([
  75647. BABYLON.serialize()
  75648. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75649. __decorate([
  75650. BABYLON.serialize()
  75651. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75652. __decorate([
  75653. BABYLON.serialize()
  75654. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75655. __decorate([
  75656. BABYLON.serialize()
  75657. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75658. __decorate([
  75659. BABYLON.serialize()
  75660. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75661. __decorate([
  75662. BABYLON.serialize()
  75663. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75664. __decorate([
  75665. BABYLON.serialize()
  75666. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75667. __decorate([
  75668. BABYLON.serialize()
  75669. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75670. __decorate([
  75671. BABYLON.serialize()
  75672. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75673. __decorate([
  75674. BABYLON.serialize()
  75675. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75676. __decorate([
  75677. BABYLON.serialize()
  75678. ], DefaultRenderingPipeline.prototype, "samples", null);
  75679. __decorate([
  75680. BABYLON.serialize()
  75681. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75682. __decorate([
  75683. BABYLON.serialize()
  75684. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  75685. __decorate([
  75686. BABYLON.serialize()
  75687. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75688. __decorate([
  75689. BABYLON.serialize()
  75690. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75691. return DefaultRenderingPipeline;
  75692. }(BABYLON.PostProcessRenderPipeline));
  75693. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75694. })(BABYLON || (BABYLON = {}));
  75695. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75696. var BABYLON;
  75697. (function (BABYLON) {
  75698. /**
  75699. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75700. */
  75701. var GeometryBufferRenderer = /** @class */ (function () {
  75702. /**
  75703. * Creates a new G Buffer for the scene
  75704. * @param scene The scene the buffer belongs to
  75705. * @param ratio How big is the buffer related to the main canvas.
  75706. */
  75707. function GeometryBufferRenderer(scene, ratio) {
  75708. if (ratio === void 0) { ratio = 1; }
  75709. this._enablePosition = false;
  75710. this._scene = scene;
  75711. this._ratio = ratio;
  75712. // Render target
  75713. this._createRenderTargets();
  75714. }
  75715. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75716. /**
  75717. * Set the render list (meshes to be rendered) used in the G buffer.
  75718. */
  75719. set: function (meshes) {
  75720. this._multiRenderTarget.renderList = meshes;
  75721. },
  75722. enumerable: true,
  75723. configurable: true
  75724. });
  75725. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75726. /**
  75727. * Gets wether or not G buffer are supported by the running hardware.
  75728. * This requires draw buffer supports
  75729. */
  75730. get: function () {
  75731. return this._multiRenderTarget.isSupported;
  75732. },
  75733. enumerable: true,
  75734. configurable: true
  75735. });
  75736. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75737. /**
  75738. * Gets wether or not position are enabled for the G buffer.
  75739. */
  75740. get: function () {
  75741. return this._enablePosition;
  75742. },
  75743. /**
  75744. * Sets wether or not position are enabled for the G buffer.
  75745. */
  75746. set: function (enable) {
  75747. this._enablePosition = enable;
  75748. this.dispose();
  75749. this._createRenderTargets();
  75750. },
  75751. enumerable: true,
  75752. configurable: true
  75753. });
  75754. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75755. /**
  75756. * Gets the scene associated with the buffer.
  75757. */
  75758. get: function () {
  75759. return this._scene;
  75760. },
  75761. enumerable: true,
  75762. configurable: true
  75763. });
  75764. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75765. /**
  75766. * Gets the ratio used by the buffer during its creation.
  75767. * How big is the buffer related to the main canvas.
  75768. */
  75769. get: function () {
  75770. return this._ratio;
  75771. },
  75772. enumerable: true,
  75773. configurable: true
  75774. });
  75775. /**
  75776. * Checks wether everything is ready to render a submesh to the G buffer.
  75777. * @param subMesh the submesh to check readiness for
  75778. * @param useInstances is the mesh drawn using instance or not
  75779. * @returns true if ready otherwise false
  75780. */
  75781. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  75782. var material = subMesh.getMaterial();
  75783. if (material && material.disableDepthWrite) {
  75784. return false;
  75785. }
  75786. var defines = [];
  75787. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75788. var mesh = subMesh.getMesh();
  75789. // Alpha test
  75790. if (material && material.needAlphaTesting()) {
  75791. defines.push("#define ALPHATEST");
  75792. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75793. attribs.push(BABYLON.VertexBuffer.UVKind);
  75794. defines.push("#define UV1");
  75795. }
  75796. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75797. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75798. defines.push("#define UV2");
  75799. }
  75800. }
  75801. // Buffers
  75802. if (this._enablePosition) {
  75803. defines.push("#define POSITION");
  75804. }
  75805. // Bones
  75806. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75807. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75808. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75809. if (mesh.numBoneInfluencers > 4) {
  75810. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75811. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75812. }
  75813. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75814. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75815. }
  75816. else {
  75817. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75818. }
  75819. // Instances
  75820. if (useInstances) {
  75821. defines.push("#define INSTANCES");
  75822. attribs.push("world0");
  75823. attribs.push("world1");
  75824. attribs.push("world2");
  75825. attribs.push("world3");
  75826. }
  75827. // Get correct effect
  75828. var join = defines.join("\n");
  75829. if (this._cachedDefines !== join) {
  75830. this._cachedDefines = join;
  75831. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  75832. }
  75833. return this._effect.isReady();
  75834. };
  75835. /**
  75836. * Gets the current underlying G Buffer.
  75837. * @returns the buffer
  75838. */
  75839. GeometryBufferRenderer.prototype.getGBuffer = function () {
  75840. return this._multiRenderTarget;
  75841. };
  75842. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  75843. /**
  75844. * Gets the number of samples used to render the buffer (anti aliasing).
  75845. */
  75846. get: function () {
  75847. return this._multiRenderTarget.samples;
  75848. },
  75849. /**
  75850. * Sets the number of samples used to render the buffer (anti aliasing).
  75851. */
  75852. set: function (value) {
  75853. this._multiRenderTarget.samples = value;
  75854. },
  75855. enumerable: true,
  75856. configurable: true
  75857. });
  75858. /**
  75859. * Disposes the renderer and frees up associated resources.
  75860. */
  75861. GeometryBufferRenderer.prototype.dispose = function () {
  75862. this.getGBuffer().dispose();
  75863. };
  75864. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  75865. var _this = this;
  75866. var engine = this._scene.getEngine();
  75867. var count = this._enablePosition ? 3 : 2;
  75868. 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 });
  75869. if (!this.isSupported) {
  75870. return;
  75871. }
  75872. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75873. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75874. this._multiRenderTarget.refreshRate = 1;
  75875. this._multiRenderTarget.renderParticles = false;
  75876. this._multiRenderTarget.renderList = null;
  75877. // set default depth value to 1.0 (far away)
  75878. this._multiRenderTarget.onClearObservable.add(function (engine) {
  75879. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  75880. });
  75881. // Custom render function
  75882. var renderSubMesh = function (subMesh) {
  75883. var mesh = subMesh.getRenderingMesh();
  75884. var scene = _this._scene;
  75885. var engine = scene.getEngine();
  75886. var material = subMesh.getMaterial();
  75887. if (!material) {
  75888. return;
  75889. }
  75890. // Culling
  75891. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75892. // Managing instances
  75893. var batch = mesh._getInstancesRenderList(subMesh._id);
  75894. if (batch.mustReturn) {
  75895. return;
  75896. }
  75897. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75898. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  75899. engine.enableEffect(_this._effect);
  75900. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75901. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75902. _this._effect.setMatrix("view", scene.getViewMatrix());
  75903. // Alpha test
  75904. if (material && material.needAlphaTesting()) {
  75905. var alphaTexture = material.getAlphaTestTexture();
  75906. if (alphaTexture) {
  75907. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75908. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75909. }
  75910. }
  75911. // Bones
  75912. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75913. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75914. }
  75915. // Draw
  75916. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75917. }
  75918. };
  75919. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75920. var index;
  75921. if (depthOnlySubMeshes.length) {
  75922. engine.setColorWrite(false);
  75923. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75924. renderSubMesh(depthOnlySubMeshes.data[index]);
  75925. }
  75926. engine.setColorWrite(true);
  75927. }
  75928. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75929. renderSubMesh(opaqueSubMeshes.data[index]);
  75930. }
  75931. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75932. renderSubMesh(alphaTestSubMeshes.data[index]);
  75933. }
  75934. };
  75935. };
  75936. return GeometryBufferRenderer;
  75937. }());
  75938. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  75939. })(BABYLON || (BABYLON = {}));
  75940. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  75941. var BABYLON;
  75942. (function (BABYLON) {
  75943. /**
  75944. * This groups together the common properties used for image processing either in direct forward pass
  75945. * or through post processing effect depending on the use of the image processing pipeline in your scene
  75946. * or not.
  75947. */
  75948. var ImageProcessingConfiguration = /** @class */ (function () {
  75949. function ImageProcessingConfiguration() {
  75950. /**
  75951. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  75952. */
  75953. this.colorCurves = new BABYLON.ColorCurves();
  75954. this._colorCurvesEnabled = false;
  75955. this._colorGradingEnabled = false;
  75956. this._colorGradingWithGreenDepth = true;
  75957. this._colorGradingBGR = true;
  75958. this._exposure = 1.0;
  75959. this._toneMappingEnabled = false;
  75960. this._contrast = 1.0;
  75961. /**
  75962. * Vignette stretch size.
  75963. */
  75964. this.vignetteStretch = 0;
  75965. /**
  75966. * Vignette centre X Offset.
  75967. */
  75968. this.vignetteCentreX = 0;
  75969. /**
  75970. * Vignette centre Y Offset.
  75971. */
  75972. this.vignetteCentreY = 0;
  75973. /**
  75974. * Vignette weight or intensity of the vignette effect.
  75975. */
  75976. this.vignetteWeight = 1.5;
  75977. /**
  75978. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75979. * if vignetteEnabled is set to true.
  75980. */
  75981. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  75982. /**
  75983. * Camera field of view used by the Vignette effect.
  75984. */
  75985. this.vignetteCameraFov = 0.5;
  75986. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  75987. this._vignetteEnabled = false;
  75988. this._applyByPostProcess = false;
  75989. this._isEnabled = true;
  75990. /**
  75991. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  75992. */
  75993. this.onUpdateParameters = new BABYLON.Observable();
  75994. }
  75995. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  75996. /**
  75997. * Gets wether the color curves effect is enabled.
  75998. */
  75999. get: function () {
  76000. return this._colorCurvesEnabled;
  76001. },
  76002. /**
  76003. * Sets wether the color curves effect is enabled.
  76004. */
  76005. set: function (value) {
  76006. if (this._colorCurvesEnabled === value) {
  76007. return;
  76008. }
  76009. this._colorCurvesEnabled = value;
  76010. this._updateParameters();
  76011. },
  76012. enumerable: true,
  76013. configurable: true
  76014. });
  76015. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  76016. /**
  76017. * Gets wether the color grading effect is enabled.
  76018. */
  76019. get: function () {
  76020. return this._colorGradingEnabled;
  76021. },
  76022. /**
  76023. * Sets wether the color grading effect is enabled.
  76024. */
  76025. set: function (value) {
  76026. if (this._colorGradingEnabled === value) {
  76027. return;
  76028. }
  76029. this._colorGradingEnabled = value;
  76030. this._updateParameters();
  76031. },
  76032. enumerable: true,
  76033. configurable: true
  76034. });
  76035. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76036. /**
  76037. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76038. */
  76039. get: function () {
  76040. return this._colorGradingWithGreenDepth;
  76041. },
  76042. /**
  76043. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76044. */
  76045. set: function (value) {
  76046. if (this._colorGradingWithGreenDepth === value) {
  76047. return;
  76048. }
  76049. this._colorGradingWithGreenDepth = value;
  76050. this._updateParameters();
  76051. },
  76052. enumerable: true,
  76053. configurable: true
  76054. });
  76055. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  76056. /**
  76057. * Gets wether the color grading texture contains BGR values.
  76058. */
  76059. get: function () {
  76060. return this._colorGradingBGR;
  76061. },
  76062. /**
  76063. * Sets wether the color grading texture contains BGR values.
  76064. */
  76065. set: function (value) {
  76066. if (this._colorGradingBGR === value) {
  76067. return;
  76068. }
  76069. this._colorGradingBGR = value;
  76070. this._updateParameters();
  76071. },
  76072. enumerable: true,
  76073. configurable: true
  76074. });
  76075. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  76076. /**
  76077. * Gets the Exposure used in the effect.
  76078. */
  76079. get: function () {
  76080. return this._exposure;
  76081. },
  76082. /**
  76083. * Sets the Exposure used in the effect.
  76084. */
  76085. set: function (value) {
  76086. if (this._exposure === value) {
  76087. return;
  76088. }
  76089. this._exposure = value;
  76090. this._updateParameters();
  76091. },
  76092. enumerable: true,
  76093. configurable: true
  76094. });
  76095. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  76096. /**
  76097. * Gets wether the tone mapping effect is enabled.
  76098. */
  76099. get: function () {
  76100. return this._toneMappingEnabled;
  76101. },
  76102. /**
  76103. * Sets wether the tone mapping effect is enabled.
  76104. */
  76105. set: function (value) {
  76106. if (this._toneMappingEnabled === value) {
  76107. return;
  76108. }
  76109. this._toneMappingEnabled = value;
  76110. this._updateParameters();
  76111. },
  76112. enumerable: true,
  76113. configurable: true
  76114. });
  76115. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  76116. /**
  76117. * Gets the contrast used in the effect.
  76118. */
  76119. get: function () {
  76120. return this._contrast;
  76121. },
  76122. /**
  76123. * Sets the contrast used in the effect.
  76124. */
  76125. set: function (value) {
  76126. if (this._contrast === value) {
  76127. return;
  76128. }
  76129. this._contrast = value;
  76130. this._updateParameters();
  76131. },
  76132. enumerable: true,
  76133. configurable: true
  76134. });
  76135. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  76136. /**
  76137. * Gets the vignette blend mode allowing different kind of effect.
  76138. */
  76139. get: function () {
  76140. return this._vignetteBlendMode;
  76141. },
  76142. /**
  76143. * Sets the vignette blend mode allowing different kind of effect.
  76144. */
  76145. set: function (value) {
  76146. if (this._vignetteBlendMode === value) {
  76147. return;
  76148. }
  76149. this._vignetteBlendMode = value;
  76150. this._updateParameters();
  76151. },
  76152. enumerable: true,
  76153. configurable: true
  76154. });
  76155. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  76156. /**
  76157. * Gets wether the vignette effect is enabled.
  76158. */
  76159. get: function () {
  76160. return this._vignetteEnabled;
  76161. },
  76162. /**
  76163. * Sets wether the vignette effect is enabled.
  76164. */
  76165. set: function (value) {
  76166. if (this._vignetteEnabled === value) {
  76167. return;
  76168. }
  76169. this._vignetteEnabled = value;
  76170. this._updateParameters();
  76171. },
  76172. enumerable: true,
  76173. configurable: true
  76174. });
  76175. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  76176. /**
  76177. * Gets wether the image processing is applied through a post process or not.
  76178. */
  76179. get: function () {
  76180. return this._applyByPostProcess;
  76181. },
  76182. /**
  76183. * Sets wether the image processing is applied through a post process or not.
  76184. */
  76185. set: function (value) {
  76186. if (this._applyByPostProcess === value) {
  76187. return;
  76188. }
  76189. this._applyByPostProcess = value;
  76190. this._updateParameters();
  76191. },
  76192. enumerable: true,
  76193. configurable: true
  76194. });
  76195. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  76196. /**
  76197. * Gets wether the image processing is enabled or not.
  76198. */
  76199. get: function () {
  76200. return this._isEnabled;
  76201. },
  76202. /**
  76203. * Sets wether the image processing is enabled or not.
  76204. */
  76205. set: function (value) {
  76206. if (this._isEnabled === value) {
  76207. return;
  76208. }
  76209. this._isEnabled = value;
  76210. this._updateParameters();
  76211. },
  76212. enumerable: true,
  76213. configurable: true
  76214. });
  76215. /**
  76216. * Method called each time the image processing information changes requires to recompile the effect.
  76217. */
  76218. ImageProcessingConfiguration.prototype._updateParameters = function () {
  76219. this.onUpdateParameters.notifyObservers(this);
  76220. };
  76221. ImageProcessingConfiguration.prototype.getClassName = function () {
  76222. return "ImageProcessingConfiguration";
  76223. };
  76224. /**
  76225. * Prepare the list of uniforms associated with the Image Processing effects.
  76226. * @param uniformsList The list of uniforms used in the effect
  76227. * @param defines the list of defines currently in use
  76228. */
  76229. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  76230. if (defines.EXPOSURE) {
  76231. uniforms.push("exposureLinear");
  76232. }
  76233. if (defines.CONTRAST) {
  76234. uniforms.push("contrast");
  76235. }
  76236. if (defines.COLORGRADING) {
  76237. uniforms.push("colorTransformSettings");
  76238. }
  76239. if (defines.VIGNETTE) {
  76240. uniforms.push("vInverseScreenSize");
  76241. uniforms.push("vignetteSettings1");
  76242. uniforms.push("vignetteSettings2");
  76243. }
  76244. if (defines.COLORCURVES) {
  76245. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  76246. }
  76247. };
  76248. /**
  76249. * Prepare the list of samplers associated with the Image Processing effects.
  76250. * @param uniformsList The list of uniforms used in the effect
  76251. * @param defines the list of defines currently in use
  76252. */
  76253. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  76254. if (defines.COLORGRADING) {
  76255. samplersList.push("txColorTransform");
  76256. }
  76257. };
  76258. /**
  76259. * Prepare the list of defines associated to the shader.
  76260. * @param defines the list of defines to complete
  76261. */
  76262. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  76263. if (forPostProcess === void 0) { forPostProcess = false; }
  76264. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  76265. defines.VIGNETTE = false;
  76266. defines.TONEMAPPING = false;
  76267. defines.CONTRAST = false;
  76268. defines.EXPOSURE = false;
  76269. defines.COLORCURVES = false;
  76270. defines.COLORGRADING = false;
  76271. defines.COLORGRADING3D = false;
  76272. defines.IMAGEPROCESSING = false;
  76273. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  76274. return;
  76275. }
  76276. defines.VIGNETTE = this.vignetteEnabled;
  76277. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  76278. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  76279. defines.TONEMAPPING = this.toneMappingEnabled;
  76280. defines.CONTRAST = (this.contrast !== 1.0);
  76281. defines.EXPOSURE = (this.exposure !== 1.0);
  76282. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  76283. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  76284. if (defines.COLORGRADING) {
  76285. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  76286. }
  76287. else {
  76288. defines.COLORGRADING3D = false;
  76289. }
  76290. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  76291. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  76292. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  76293. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  76294. };
  76295. /**
  76296. * Returns true if all the image processing information are ready.
  76297. */
  76298. ImageProcessingConfiguration.prototype.isReady = function () {
  76299. // Color Grading texure can not be none blocking.
  76300. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  76301. };
  76302. /**
  76303. * Binds the image processing to the shader.
  76304. * @param effect The effect to bind to
  76305. */
  76306. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  76307. if (aspectRatio === void 0) { aspectRatio = 1; }
  76308. // Color Curves
  76309. if (this._colorCurvesEnabled && this.colorCurves) {
  76310. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  76311. }
  76312. // Vignette
  76313. if (this._vignetteEnabled) {
  76314. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  76315. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  76316. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  76317. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  76318. var vignetteScaleX = vignetteScaleY * aspectRatio;
  76319. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  76320. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  76321. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  76322. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  76323. var vignettePower = -2.0 * this.vignetteWeight;
  76324. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  76325. }
  76326. // Exposure
  76327. effect.setFloat("exposureLinear", this.exposure);
  76328. // Contrast
  76329. effect.setFloat("contrast", this.contrast);
  76330. // Color transform settings
  76331. if (this.colorGradingTexture) {
  76332. effect.setTexture("txColorTransform", this.colorGradingTexture);
  76333. var textureSize = this.colorGradingTexture.getSize().height;
  76334. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  76335. 0.5 / textureSize, // textureOffset
  76336. textureSize, // textureSize
  76337. this.colorGradingTexture.level // weight
  76338. );
  76339. }
  76340. };
  76341. /**
  76342. * Clones the current image processing instance.
  76343. * @return The cloned image processing
  76344. */
  76345. ImageProcessingConfiguration.prototype.clone = function () {
  76346. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  76347. };
  76348. /**
  76349. * Serializes the current image processing instance to a json representation.
  76350. * @return a JSON representation
  76351. */
  76352. ImageProcessingConfiguration.prototype.serialize = function () {
  76353. return BABYLON.SerializationHelper.Serialize(this);
  76354. };
  76355. /**
  76356. * Parses the image processing from a json representation.
  76357. * @param source the JSON source to parse
  76358. * @return The parsed image processing
  76359. */
  76360. ImageProcessingConfiguration.Parse = function (source) {
  76361. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  76362. };
  76363. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  76364. /**
  76365. * Used to apply the vignette as a mix with the pixel color.
  76366. */
  76367. get: function () {
  76368. return this._VIGNETTEMODE_MULTIPLY;
  76369. },
  76370. enumerable: true,
  76371. configurable: true
  76372. });
  76373. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  76374. /**
  76375. * Used to apply the vignette as a replacement of the pixel color.
  76376. */
  76377. get: function () {
  76378. return this._VIGNETTEMODE_OPAQUE;
  76379. },
  76380. enumerable: true,
  76381. configurable: true
  76382. });
  76383. // Static constants associated to the image processing.
  76384. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  76385. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  76386. __decorate([
  76387. BABYLON.serializeAsColorCurves()
  76388. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  76389. __decorate([
  76390. BABYLON.serialize()
  76391. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  76392. __decorate([
  76393. BABYLON.serializeAsTexture()
  76394. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  76395. __decorate([
  76396. BABYLON.serialize()
  76397. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  76398. __decorate([
  76399. BABYLON.serialize()
  76400. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  76401. __decorate([
  76402. BABYLON.serialize()
  76403. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  76404. __decorate([
  76405. BABYLON.serialize()
  76406. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  76407. __decorate([
  76408. BABYLON.serialize()
  76409. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  76410. __decorate([
  76411. BABYLON.serialize()
  76412. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  76413. __decorate([
  76414. BABYLON.serialize()
  76415. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  76416. __decorate([
  76417. BABYLON.serialize()
  76418. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  76419. __decorate([
  76420. BABYLON.serialize()
  76421. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  76422. __decorate([
  76423. BABYLON.serialize()
  76424. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  76425. __decorate([
  76426. BABYLON.serializeAsColor4()
  76427. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  76428. __decorate([
  76429. BABYLON.serialize()
  76430. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  76431. __decorate([
  76432. BABYLON.serialize()
  76433. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  76434. __decorate([
  76435. BABYLON.serialize()
  76436. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  76437. __decorate([
  76438. BABYLON.serialize()
  76439. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  76440. __decorate([
  76441. BABYLON.serialize()
  76442. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  76443. return ImageProcessingConfiguration;
  76444. }());
  76445. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  76446. })(BABYLON || (BABYLON = {}));
  76447. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  76448. var BABYLON;
  76449. (function (BABYLON) {
  76450. /**
  76451. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  76452. * It can help converting any input color in a desired output one. This can then be used to create effects
  76453. * from sepia, black and white to sixties or futuristic rendering...
  76454. *
  76455. * The only supported format is currently 3dl.
  76456. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  76457. */
  76458. var ColorGradingTexture = /** @class */ (function (_super) {
  76459. __extends(ColorGradingTexture, _super);
  76460. /**
  76461. * Instantiates a ColorGradingTexture from the following parameters.
  76462. *
  76463. * @param url The location of the color gradind data (currently only supporting 3dl)
  76464. * @param scene The scene the texture will be used in
  76465. */
  76466. function ColorGradingTexture(url, scene) {
  76467. var _this = _super.call(this, scene) || this;
  76468. if (!url) {
  76469. return _this;
  76470. }
  76471. _this._engine = scene.getEngine();
  76472. _this._textureMatrix = BABYLON.Matrix.Identity();
  76473. _this.name = url;
  76474. _this.url = url;
  76475. _this.hasAlpha = false;
  76476. _this.isCube = false;
  76477. _this.is3D = _this._engine.webGLVersion > 1;
  76478. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76479. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76480. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76481. _this.anisotropicFilteringLevel = 1;
  76482. _this._texture = _this._getFromCache(url, true);
  76483. if (!_this._texture) {
  76484. if (!scene.useDelayedTextureLoading) {
  76485. _this.loadTexture();
  76486. }
  76487. else {
  76488. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  76489. }
  76490. }
  76491. return _this;
  76492. }
  76493. /**
  76494. * Returns the texture matrix used in most of the material.
  76495. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  76496. */
  76497. ColorGradingTexture.prototype.getTextureMatrix = function () {
  76498. return this._textureMatrix;
  76499. };
  76500. /**
  76501. * Occurs when the file being loaded is a .3dl LUT file.
  76502. */
  76503. ColorGradingTexture.prototype.load3dlTexture = function () {
  76504. var engine = this._engine;
  76505. var texture;
  76506. if (engine.webGLVersion === 1) {
  76507. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76508. }
  76509. else {
  76510. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76511. }
  76512. this._texture = texture;
  76513. var callback = function (text) {
  76514. if (typeof text !== "string") {
  76515. return;
  76516. }
  76517. var data = null;
  76518. var tempData = null;
  76519. var line;
  76520. var lines = text.split('\n');
  76521. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  76522. var maxColor = 0;
  76523. for (var i = 0; i < lines.length; i++) {
  76524. line = lines[i];
  76525. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  76526. continue;
  76527. if (line.indexOf('#') === 0)
  76528. continue;
  76529. var words = line.split(" ");
  76530. if (size === 0) {
  76531. // Number of space + one
  76532. size = words.length;
  76533. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  76534. tempData = new Float32Array(size * size * size * 4);
  76535. continue;
  76536. }
  76537. if (size != 0) {
  76538. var r = Math.max(parseInt(words[0]), 0);
  76539. var g = Math.max(parseInt(words[1]), 0);
  76540. var b = Math.max(parseInt(words[2]), 0);
  76541. maxColor = Math.max(r, maxColor);
  76542. maxColor = Math.max(g, maxColor);
  76543. maxColor = Math.max(b, maxColor);
  76544. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  76545. if (tempData) {
  76546. tempData[pixelStorageIndex + 0] = r;
  76547. tempData[pixelStorageIndex + 1] = g;
  76548. tempData[pixelStorageIndex + 2] = b;
  76549. }
  76550. pixelIndexSlice++;
  76551. if (pixelIndexSlice % size == 0) {
  76552. pixelIndexH++;
  76553. pixelIndexSlice = 0;
  76554. if (pixelIndexH % size == 0) {
  76555. pixelIndexW++;
  76556. pixelIndexH = 0;
  76557. }
  76558. }
  76559. }
  76560. }
  76561. if (tempData && data) {
  76562. for (var i = 0; i < tempData.length; i++) {
  76563. if (i > 0 && (i + 1) % 4 === 0) {
  76564. data[i] = 255;
  76565. }
  76566. else {
  76567. var value = tempData[i];
  76568. data[i] = (value / maxColor * 255);
  76569. }
  76570. }
  76571. }
  76572. if (texture.is3D) {
  76573. texture.updateSize(size, size, size);
  76574. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  76575. }
  76576. else {
  76577. texture.updateSize(size * size, size);
  76578. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  76579. }
  76580. };
  76581. var scene = this.getScene();
  76582. if (scene) {
  76583. scene._loadFile(this.url, callback);
  76584. }
  76585. else {
  76586. this._engine._loadFile(this.url, callback);
  76587. }
  76588. return this._texture;
  76589. };
  76590. /**
  76591. * Starts the loading process of the texture.
  76592. */
  76593. ColorGradingTexture.prototype.loadTexture = function () {
  76594. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  76595. this.load3dlTexture();
  76596. }
  76597. };
  76598. /**
  76599. * Clones the color gradind texture.
  76600. */
  76601. ColorGradingTexture.prototype.clone = function () {
  76602. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  76603. // Base texture
  76604. newTexture.level = this.level;
  76605. return newTexture;
  76606. };
  76607. /**
  76608. * Called during delayed load for textures.
  76609. */
  76610. ColorGradingTexture.prototype.delayLoad = function () {
  76611. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  76612. return;
  76613. }
  76614. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  76615. this._texture = this._getFromCache(this.url, true);
  76616. if (!this._texture) {
  76617. this.loadTexture();
  76618. }
  76619. };
  76620. /**
  76621. * Parses a color grading texture serialized by Babylon.
  76622. * @param parsedTexture The texture information being parsedTexture
  76623. * @param scene The scene to load the texture in
  76624. * @param rootUrl The root url of the data assets to load
  76625. * @return A color gradind texture
  76626. */
  76627. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  76628. var texture = null;
  76629. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  76630. texture = new ColorGradingTexture(parsedTexture.name, scene);
  76631. texture.name = parsedTexture.name;
  76632. texture.level = parsedTexture.level;
  76633. }
  76634. return texture;
  76635. };
  76636. /**
  76637. * Serializes the LUT texture to json format.
  76638. */
  76639. ColorGradingTexture.prototype.serialize = function () {
  76640. if (!this.name) {
  76641. return null;
  76642. }
  76643. var serializationObject = {};
  76644. serializationObject.name = this.name;
  76645. serializationObject.level = this.level;
  76646. serializationObject.customType = "BABYLON.ColorGradingTexture";
  76647. return serializationObject;
  76648. };
  76649. /**
  76650. * Empty line regex stored for GC.
  76651. */
  76652. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  76653. return ColorGradingTexture;
  76654. }(BABYLON.BaseTexture));
  76655. BABYLON.ColorGradingTexture = ColorGradingTexture;
  76656. })(BABYLON || (BABYLON = {}));
  76657. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  76658. var BABYLON;
  76659. (function (BABYLON) {
  76660. /**
  76661. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76662. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76663. * 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;
  76664. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76665. */
  76666. var ColorCurves = /** @class */ (function () {
  76667. function ColorCurves() {
  76668. this._dirty = true;
  76669. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  76670. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  76671. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  76672. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  76673. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  76674. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  76675. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  76676. this._globalHue = 30;
  76677. this._globalDensity = 0;
  76678. this._globalSaturation = 0;
  76679. this._globalExposure = 0;
  76680. this._highlightsHue = 30;
  76681. this._highlightsDensity = 0;
  76682. this._highlightsSaturation = 0;
  76683. this._highlightsExposure = 0;
  76684. this._midtonesHue = 30;
  76685. this._midtonesDensity = 0;
  76686. this._midtonesSaturation = 0;
  76687. this._midtonesExposure = 0;
  76688. this._shadowsHue = 30;
  76689. this._shadowsDensity = 0;
  76690. this._shadowsSaturation = 0;
  76691. this._shadowsExposure = 0;
  76692. }
  76693. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  76694. /**
  76695. * Gets the global Hue value.
  76696. * 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).
  76697. */
  76698. get: function () {
  76699. return this._globalHue;
  76700. },
  76701. /**
  76702. * Sets the global Hue value.
  76703. * 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).
  76704. */
  76705. set: function (value) {
  76706. this._globalHue = value;
  76707. this._dirty = true;
  76708. },
  76709. enumerable: true,
  76710. configurable: true
  76711. });
  76712. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  76713. /**
  76714. * Gets the global Density value.
  76715. * 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.
  76716. * Values less than zero provide a filter of opposite hue.
  76717. */
  76718. get: function () {
  76719. return this._globalDensity;
  76720. },
  76721. /**
  76722. * Sets the global Density value.
  76723. * 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.
  76724. * Values less than zero provide a filter of opposite hue.
  76725. */
  76726. set: function (value) {
  76727. this._globalDensity = value;
  76728. this._dirty = true;
  76729. },
  76730. enumerable: true,
  76731. configurable: true
  76732. });
  76733. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  76734. /**
  76735. * Gets the global Saturation value.
  76736. * 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.
  76737. */
  76738. get: function () {
  76739. return this._globalSaturation;
  76740. },
  76741. /**
  76742. * Sets the global Saturation value.
  76743. * 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.
  76744. */
  76745. set: function (value) {
  76746. this._globalSaturation = value;
  76747. this._dirty = true;
  76748. },
  76749. enumerable: true,
  76750. configurable: true
  76751. });
  76752. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  76753. /**
  76754. * Gets the global Exposure value.
  76755. * 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.
  76756. */
  76757. get: function () {
  76758. return this._globalExposure;
  76759. },
  76760. /**
  76761. * Sets the global Exposure value.
  76762. * 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.
  76763. */
  76764. set: function (value) {
  76765. this._globalExposure = value;
  76766. this._dirty = true;
  76767. },
  76768. enumerable: true,
  76769. configurable: true
  76770. });
  76771. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  76772. /**
  76773. * Gets the highlights Hue value.
  76774. * 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).
  76775. */
  76776. get: function () {
  76777. return this._highlightsHue;
  76778. },
  76779. /**
  76780. * Sets the highlights Hue value.
  76781. * 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).
  76782. */
  76783. set: function (value) {
  76784. this._highlightsHue = value;
  76785. this._dirty = true;
  76786. },
  76787. enumerable: true,
  76788. configurable: true
  76789. });
  76790. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  76791. /**
  76792. * Gets the highlights Density value.
  76793. * 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.
  76794. * Values less than zero provide a filter of opposite hue.
  76795. */
  76796. get: function () {
  76797. return this._highlightsDensity;
  76798. },
  76799. /**
  76800. * Sets the highlights Density value.
  76801. * 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.
  76802. * Values less than zero provide a filter of opposite hue.
  76803. */
  76804. set: function (value) {
  76805. this._highlightsDensity = value;
  76806. this._dirty = true;
  76807. },
  76808. enumerable: true,
  76809. configurable: true
  76810. });
  76811. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  76812. /**
  76813. * Gets the highlights Saturation value.
  76814. * 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.
  76815. */
  76816. get: function () {
  76817. return this._highlightsSaturation;
  76818. },
  76819. /**
  76820. * Sets the highlights Saturation value.
  76821. * 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.
  76822. */
  76823. set: function (value) {
  76824. this._highlightsSaturation = value;
  76825. this._dirty = true;
  76826. },
  76827. enumerable: true,
  76828. configurable: true
  76829. });
  76830. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  76831. /**
  76832. * Gets the highlights Exposure value.
  76833. * 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.
  76834. */
  76835. get: function () {
  76836. return this._highlightsExposure;
  76837. },
  76838. /**
  76839. * Sets the highlights Exposure value.
  76840. * 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.
  76841. */
  76842. set: function (value) {
  76843. this._highlightsExposure = value;
  76844. this._dirty = true;
  76845. },
  76846. enumerable: true,
  76847. configurable: true
  76848. });
  76849. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  76850. /**
  76851. * Gets the midtones Hue value.
  76852. * 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).
  76853. */
  76854. get: function () {
  76855. return this._midtonesHue;
  76856. },
  76857. /**
  76858. * Sets the midtones Hue value.
  76859. * 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).
  76860. */
  76861. set: function (value) {
  76862. this._midtonesHue = value;
  76863. this._dirty = true;
  76864. },
  76865. enumerable: true,
  76866. configurable: true
  76867. });
  76868. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  76869. /**
  76870. * Gets the midtones Density value.
  76871. * 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.
  76872. * Values less than zero provide a filter of opposite hue.
  76873. */
  76874. get: function () {
  76875. return this._midtonesDensity;
  76876. },
  76877. /**
  76878. * Sets the midtones Density value.
  76879. * 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.
  76880. * Values less than zero provide a filter of opposite hue.
  76881. */
  76882. set: function (value) {
  76883. this._midtonesDensity = value;
  76884. this._dirty = true;
  76885. },
  76886. enumerable: true,
  76887. configurable: true
  76888. });
  76889. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  76890. /**
  76891. * Gets the midtones Saturation value.
  76892. * 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.
  76893. */
  76894. get: function () {
  76895. return this._midtonesSaturation;
  76896. },
  76897. /**
  76898. * Sets the midtones Saturation value.
  76899. * 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.
  76900. */
  76901. set: function (value) {
  76902. this._midtonesSaturation = value;
  76903. this._dirty = true;
  76904. },
  76905. enumerable: true,
  76906. configurable: true
  76907. });
  76908. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  76909. /**
  76910. * Gets the midtones Exposure value.
  76911. * 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.
  76912. */
  76913. get: function () {
  76914. return this._midtonesExposure;
  76915. },
  76916. /**
  76917. * Sets the midtones Exposure value.
  76918. * 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.
  76919. */
  76920. set: function (value) {
  76921. this._midtonesExposure = value;
  76922. this._dirty = true;
  76923. },
  76924. enumerable: true,
  76925. configurable: true
  76926. });
  76927. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  76928. /**
  76929. * Gets the shadows Hue value.
  76930. * 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).
  76931. */
  76932. get: function () {
  76933. return this._shadowsHue;
  76934. },
  76935. /**
  76936. * Sets the shadows Hue value.
  76937. * 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).
  76938. */
  76939. set: function (value) {
  76940. this._shadowsHue = value;
  76941. this._dirty = true;
  76942. },
  76943. enumerable: true,
  76944. configurable: true
  76945. });
  76946. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  76947. /**
  76948. * Gets the shadows Density value.
  76949. * 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.
  76950. * Values less than zero provide a filter of opposite hue.
  76951. */
  76952. get: function () {
  76953. return this._shadowsDensity;
  76954. },
  76955. /**
  76956. * Sets the shadows Density value.
  76957. * 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.
  76958. * Values less than zero provide a filter of opposite hue.
  76959. */
  76960. set: function (value) {
  76961. this._shadowsDensity = value;
  76962. this._dirty = true;
  76963. },
  76964. enumerable: true,
  76965. configurable: true
  76966. });
  76967. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  76968. /**
  76969. * Gets the shadows Saturation value.
  76970. * 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.
  76971. */
  76972. get: function () {
  76973. return this._shadowsSaturation;
  76974. },
  76975. /**
  76976. * Sets the shadows Saturation value.
  76977. * 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.
  76978. */
  76979. set: function (value) {
  76980. this._shadowsSaturation = value;
  76981. this._dirty = true;
  76982. },
  76983. enumerable: true,
  76984. configurable: true
  76985. });
  76986. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  76987. /**
  76988. * Gets the shadows Exposure value.
  76989. * 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.
  76990. */
  76991. get: function () {
  76992. return this._shadowsExposure;
  76993. },
  76994. /**
  76995. * Sets the shadows Exposure value.
  76996. * 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.
  76997. */
  76998. set: function (value) {
  76999. this._shadowsExposure = value;
  77000. this._dirty = true;
  77001. },
  77002. enumerable: true,
  77003. configurable: true
  77004. });
  77005. ColorCurves.prototype.getClassName = function () {
  77006. return "ColorCurves";
  77007. };
  77008. /**
  77009. * Binds the color curves to the shader.
  77010. * @param colorCurves The color curve to bind
  77011. * @param effect The effect to bind to
  77012. */
  77013. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  77014. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  77015. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  77016. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  77017. if (colorCurves._dirty) {
  77018. colorCurves._dirty = false;
  77019. // Fill in global info.
  77020. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  77021. // Compute highlights info.
  77022. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  77023. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  77024. // Compute midtones info.
  77025. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  77026. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77027. // Compute shadows info.
  77028. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77029. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77030. // Compute deltas (neutral is midtones).
  77031. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77032. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77033. }
  77034. if (effect) {
  77035. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77036. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77037. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77038. }
  77039. };
  77040. /**
  77041. * Prepare the list of uniforms associated with the ColorCurves effects.
  77042. * @param uniformsList The list of uniforms used in the effect
  77043. */
  77044. ColorCurves.PrepareUniforms = function (uniformsList) {
  77045. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77046. };
  77047. /**
  77048. * Returns color grading data based on a hue, density, saturation and exposure value.
  77049. * @param filterHue The hue of the color filter.
  77050. * @param filterDensity The density of the color filter.
  77051. * @param saturation The saturation.
  77052. * @param exposure The exposure.
  77053. * @param result The result data container.
  77054. */
  77055. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  77056. if (hue == null) {
  77057. return;
  77058. }
  77059. hue = ColorCurves.clamp(hue, 0, 360);
  77060. density = ColorCurves.clamp(density, -100, 100);
  77061. saturation = ColorCurves.clamp(saturation, -100, 100);
  77062. exposure = ColorCurves.clamp(exposure, -100, 100);
  77063. // Remap the slider/config filter density with non-linear mapping and also scale by half
  77064. // so that the maximum filter density is only 50% control. This provides fine control
  77065. // for small values and reasonable range.
  77066. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  77067. density *= 0.5;
  77068. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  77069. if (density < 0) {
  77070. density *= -1;
  77071. hue = (hue + 180) % 360;
  77072. }
  77073. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  77074. result.scaleToRef(2, result);
  77075. result.a = 1 + 0.01 * saturation;
  77076. };
  77077. /**
  77078. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  77079. * @param value The input slider value in range [-100,100].
  77080. * @returns Adjusted value.
  77081. */
  77082. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  77083. value /= 100;
  77084. var x = Math.abs(value);
  77085. x = Math.pow(x, 2);
  77086. if (value < 0) {
  77087. x *= -1;
  77088. }
  77089. x *= 100;
  77090. return x;
  77091. };
  77092. /**
  77093. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  77094. * @param hue The hue (H) input.
  77095. * @param saturation The saturation (S) input.
  77096. * @param brightness The brightness (B) input.
  77097. * @result An RGBA color represented as Vector4.
  77098. */
  77099. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  77100. var h = ColorCurves.clamp(hue, 0, 360);
  77101. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  77102. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  77103. if (s === 0) {
  77104. result.r = v;
  77105. result.g = v;
  77106. result.b = v;
  77107. }
  77108. else {
  77109. // sector 0 to 5
  77110. h /= 60;
  77111. var i = Math.floor(h);
  77112. // fractional part of h
  77113. var f = h - i;
  77114. var p = v * (1 - s);
  77115. var q = v * (1 - s * f);
  77116. var t = v * (1 - s * (1 - f));
  77117. switch (i) {
  77118. case 0:
  77119. result.r = v;
  77120. result.g = t;
  77121. result.b = p;
  77122. break;
  77123. case 1:
  77124. result.r = q;
  77125. result.g = v;
  77126. result.b = p;
  77127. break;
  77128. case 2:
  77129. result.r = p;
  77130. result.g = v;
  77131. result.b = t;
  77132. break;
  77133. case 3:
  77134. result.r = p;
  77135. result.g = q;
  77136. result.b = v;
  77137. break;
  77138. case 4:
  77139. result.r = t;
  77140. result.g = p;
  77141. result.b = v;
  77142. break;
  77143. default: // case 5:
  77144. result.r = v;
  77145. result.g = p;
  77146. result.b = q;
  77147. break;
  77148. }
  77149. }
  77150. result.a = 1;
  77151. };
  77152. /**
  77153. * Returns a value clamped between min and max
  77154. * @param value The value to clamp
  77155. * @param min The minimum of value
  77156. * @param max The maximum of value
  77157. * @returns The clamped value.
  77158. */
  77159. ColorCurves.clamp = function (value, min, max) {
  77160. return Math.min(Math.max(value, min), max);
  77161. };
  77162. /**
  77163. * Clones the current color curve instance.
  77164. * @return The cloned curves
  77165. */
  77166. ColorCurves.prototype.clone = function () {
  77167. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  77168. };
  77169. /**
  77170. * Serializes the current color curve instance to a json representation.
  77171. * @return a JSON representation
  77172. */
  77173. ColorCurves.prototype.serialize = function () {
  77174. return BABYLON.SerializationHelper.Serialize(this);
  77175. };
  77176. /**
  77177. * Parses the color curve from a json representation.
  77178. * @param source the JSON source to parse
  77179. * @return The parsed curves
  77180. */
  77181. ColorCurves.Parse = function (source) {
  77182. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  77183. };
  77184. __decorate([
  77185. BABYLON.serialize()
  77186. ], ColorCurves.prototype, "_globalHue", void 0);
  77187. __decorate([
  77188. BABYLON.serialize()
  77189. ], ColorCurves.prototype, "_globalDensity", void 0);
  77190. __decorate([
  77191. BABYLON.serialize()
  77192. ], ColorCurves.prototype, "_globalSaturation", void 0);
  77193. __decorate([
  77194. BABYLON.serialize()
  77195. ], ColorCurves.prototype, "_globalExposure", void 0);
  77196. __decorate([
  77197. BABYLON.serialize()
  77198. ], ColorCurves.prototype, "_highlightsHue", void 0);
  77199. __decorate([
  77200. BABYLON.serialize()
  77201. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  77202. __decorate([
  77203. BABYLON.serialize()
  77204. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  77205. __decorate([
  77206. BABYLON.serialize()
  77207. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  77208. __decorate([
  77209. BABYLON.serialize()
  77210. ], ColorCurves.prototype, "_midtonesHue", void 0);
  77211. __decorate([
  77212. BABYLON.serialize()
  77213. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  77214. __decorate([
  77215. BABYLON.serialize()
  77216. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  77217. __decorate([
  77218. BABYLON.serialize()
  77219. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  77220. return ColorCurves;
  77221. }());
  77222. BABYLON.ColorCurves = ColorCurves;
  77223. })(BABYLON || (BABYLON = {}));
  77224. //# sourceMappingURL=babylon.colorCurves.js.map
  77225. var BABYLON;
  77226. (function (BABYLON) {
  77227. var RefractionPostProcess = /** @class */ (function (_super) {
  77228. __extends(RefractionPostProcess, _super);
  77229. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77230. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77231. _this.color = color;
  77232. _this.depth = depth;
  77233. _this.colorLevel = colorLevel;
  77234. _this._ownRefractionTexture = true;
  77235. _this.onActivateObservable.add(function (cam) {
  77236. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77237. });
  77238. _this.onApplyObservable.add(function (effect) {
  77239. effect.setColor3("baseColor", _this.color);
  77240. effect.setFloat("depth", _this.depth);
  77241. effect.setFloat("colorLevel", _this.colorLevel);
  77242. effect.setTexture("refractionSampler", _this._refTexture);
  77243. });
  77244. return _this;
  77245. }
  77246. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77247. /**
  77248. * Gets or sets the refraction texture
  77249. * Please note that you are responsible for disposing the texture if you set it manually
  77250. */
  77251. get: function () {
  77252. return this._refTexture;
  77253. },
  77254. set: function (value) {
  77255. if (this._refTexture && this._ownRefractionTexture) {
  77256. this._refTexture.dispose();
  77257. }
  77258. this._refTexture = value;
  77259. this._ownRefractionTexture = false;
  77260. },
  77261. enumerable: true,
  77262. configurable: true
  77263. });
  77264. // Methods
  77265. RefractionPostProcess.prototype.dispose = function (camera) {
  77266. if (this._refTexture && this._ownRefractionTexture) {
  77267. this._refTexture.dispose();
  77268. this._refTexture = null;
  77269. }
  77270. _super.prototype.dispose.call(this, camera);
  77271. };
  77272. return RefractionPostProcess;
  77273. }(BABYLON.PostProcess));
  77274. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77275. })(BABYLON || (BABYLON = {}));
  77276. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77277. var BABYLON;
  77278. (function (BABYLON) {
  77279. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77280. __extends(BlackAndWhitePostProcess, _super);
  77281. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77282. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77283. _this.degree = 1;
  77284. _this.onApplyObservable.add(function (effect) {
  77285. effect.setFloat("degree", _this.degree);
  77286. });
  77287. return _this;
  77288. }
  77289. return BlackAndWhitePostProcess;
  77290. }(BABYLON.PostProcess));
  77291. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77292. })(BABYLON || (BABYLON = {}));
  77293. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77294. var BABYLON;
  77295. (function (BABYLON) {
  77296. /**
  77297. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77298. * input texture to perform effects such as edge detection or sharpening
  77299. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77300. */
  77301. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77302. __extends(ConvolutionPostProcess, _super);
  77303. /**
  77304. * Creates a new instance ConvolutionPostProcess
  77305. * @param name The name of the effect.
  77306. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77307. * @param options The required width/height ratio to downsize to before computing the render pass.
  77308. * @param camera The camera to apply the render pass to.
  77309. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77310. * @param engine The engine which the post process will be applied. (default: current engine)
  77311. * @param reusable If the post process can be reused on the same frame. (default: false)
  77312. * @param textureType Type of textures used when performing the post process. (default: 0)
  77313. */
  77314. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77315. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77316. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77317. _this.kernel = kernel;
  77318. _this.onApply = function (effect) {
  77319. effect.setFloat2("screenSize", _this.width, _this.height);
  77320. effect.setArray("kernel", _this.kernel);
  77321. };
  77322. return _this;
  77323. }
  77324. // Statics
  77325. /**
  77326. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77327. */
  77328. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77329. /**
  77330. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77331. */
  77332. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77333. /**
  77334. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77335. */
  77336. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77337. /**
  77338. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77339. */
  77340. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77341. /**
  77342. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77343. */
  77344. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77345. /**
  77346. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77347. */
  77348. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77349. return ConvolutionPostProcess;
  77350. }(BABYLON.PostProcess));
  77351. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77352. })(BABYLON || (BABYLON = {}));
  77353. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77354. var BABYLON;
  77355. (function (BABYLON) {
  77356. var FilterPostProcess = /** @class */ (function (_super) {
  77357. __extends(FilterPostProcess, _super);
  77358. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77359. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77360. _this.kernelMatrix = kernelMatrix;
  77361. _this.onApply = function (effect) {
  77362. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77363. };
  77364. return _this;
  77365. }
  77366. return FilterPostProcess;
  77367. }(BABYLON.PostProcess));
  77368. BABYLON.FilterPostProcess = FilterPostProcess;
  77369. })(BABYLON || (BABYLON = {}));
  77370. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77371. var BABYLON;
  77372. (function (BABYLON) {
  77373. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77374. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77375. __extends(VolumetricLightScatteringPostProcess, _super);
  77376. /**
  77377. * @constructor
  77378. * @param {string} name - The post-process name
  77379. * @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)
  77380. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77381. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77382. * @param {number} samples - The post-process quality, default 100
  77383. * @param {number} samplingMode - The post-process filtering mode
  77384. * @param {BABYLON.Engine} engine - The babylon engine
  77385. * @param {boolean} reusable - If the post-process is reusable
  77386. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77387. */
  77388. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77389. if (samples === void 0) { samples = 100; }
  77390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77391. 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;
  77392. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77393. /**
  77394. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77395. */
  77396. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77397. /**
  77398. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77399. */
  77400. _this.useCustomMeshPosition = false;
  77401. /**
  77402. * If the post-process should inverse the light scattering direction
  77403. */
  77404. _this.invert = true;
  77405. /**
  77406. * Array containing the excluded meshes not rendered in the internal pass
  77407. */
  77408. _this.excludedMeshes = new Array();
  77409. /**
  77410. * Controls the overall intensity of the post-process
  77411. */
  77412. _this.exposure = 0.3;
  77413. /**
  77414. * Dissipates each sample's contribution in range [0, 1]
  77415. */
  77416. _this.decay = 0.96815;
  77417. /**
  77418. * Controls the overall intensity of each sample
  77419. */
  77420. _this.weight = 0.58767;
  77421. /**
  77422. * Controls the density of each sample
  77423. */
  77424. _this.density = 0.926;
  77425. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77426. engine = scene.getEngine();
  77427. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77428. // Configure mesh
  77429. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77430. // Configure
  77431. _this._createPass(scene, ratio.passRatio || ratio);
  77432. _this.onActivate = function (camera) {
  77433. if (!_this.isSupported) {
  77434. _this.dispose(camera);
  77435. }
  77436. _this.onActivate = null;
  77437. };
  77438. _this.onApplyObservable.add(function (effect) {
  77439. _this._updateMeshScreenCoordinates(scene);
  77440. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77441. effect.setFloat("exposure", _this.exposure);
  77442. effect.setFloat("decay", _this.decay);
  77443. effect.setFloat("weight", _this.weight);
  77444. effect.setFloat("density", _this.density);
  77445. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77446. });
  77447. return _this;
  77448. }
  77449. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77450. get: function () {
  77451. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77452. return false;
  77453. },
  77454. set: function (useDiffuseColor) {
  77455. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77456. },
  77457. enumerable: true,
  77458. configurable: true
  77459. });
  77460. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77461. return "VolumetricLightScatteringPostProcess";
  77462. };
  77463. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77464. var mesh = subMesh.getMesh();
  77465. // Render this.mesh as default
  77466. if (mesh === this.mesh && mesh.material) {
  77467. return mesh.material.isReady(mesh);
  77468. }
  77469. var defines = [];
  77470. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77471. var material = subMesh.getMaterial();
  77472. // Alpha test
  77473. if (material) {
  77474. if (material.needAlphaTesting()) {
  77475. defines.push("#define ALPHATEST");
  77476. }
  77477. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77478. attribs.push(BABYLON.VertexBuffer.UVKind);
  77479. defines.push("#define UV1");
  77480. }
  77481. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77482. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77483. defines.push("#define UV2");
  77484. }
  77485. }
  77486. // Bones
  77487. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77488. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77489. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77490. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77491. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77492. }
  77493. else {
  77494. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77495. }
  77496. // Instances
  77497. if (useInstances) {
  77498. defines.push("#define INSTANCES");
  77499. attribs.push("world0");
  77500. attribs.push("world1");
  77501. attribs.push("world2");
  77502. attribs.push("world3");
  77503. }
  77504. // Get correct effect
  77505. var join = defines.join("\n");
  77506. if (this._cachedDefines !== join) {
  77507. this._cachedDefines = join;
  77508. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77509. }
  77510. return this._volumetricLightScatteringPass.isReady();
  77511. };
  77512. /**
  77513. * Sets the new light position for light scattering effect
  77514. * @param {BABYLON.Vector3} The new custom light position
  77515. */
  77516. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77517. this.customMeshPosition = position;
  77518. };
  77519. /**
  77520. * Returns the light position for light scattering effect
  77521. * @return {BABYLON.Vector3} The custom light position
  77522. */
  77523. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77524. return this.customMeshPosition;
  77525. };
  77526. /**
  77527. * Disposes the internal assets and detaches the post-process from the camera
  77528. */
  77529. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77530. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77531. if (rttIndex !== -1) {
  77532. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77533. }
  77534. this._volumetricLightScatteringRTT.dispose();
  77535. _super.prototype.dispose.call(this, camera);
  77536. };
  77537. /**
  77538. * Returns the render target texture used by the post-process
  77539. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77540. */
  77541. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77542. return this._volumetricLightScatteringRTT;
  77543. };
  77544. // Private methods
  77545. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77546. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77547. return true;
  77548. }
  77549. return false;
  77550. };
  77551. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77552. var _this = this;
  77553. var engine = scene.getEngine();
  77554. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77555. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77556. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77557. this._volumetricLightScatteringRTT.renderList = null;
  77558. this._volumetricLightScatteringRTT.renderParticles = false;
  77559. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77560. var camera = this.getCamera();
  77561. if (camera) {
  77562. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77563. }
  77564. else {
  77565. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77566. }
  77567. // Custom render function for submeshes
  77568. var renderSubMesh = function (subMesh) {
  77569. var mesh = subMesh.getRenderingMesh();
  77570. if (_this._meshExcluded(mesh)) {
  77571. return;
  77572. }
  77573. var material = subMesh.getMaterial();
  77574. if (!material) {
  77575. return;
  77576. }
  77577. var scene = mesh.getScene();
  77578. var engine = scene.getEngine();
  77579. // Culling
  77580. engine.setState(material.backFaceCulling);
  77581. // Managing instances
  77582. var batch = mesh._getInstancesRenderList(subMesh._id);
  77583. if (batch.mustReturn) {
  77584. return;
  77585. }
  77586. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77587. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77588. var effect = _this._volumetricLightScatteringPass;
  77589. if (mesh === _this.mesh) {
  77590. if (subMesh.effect) {
  77591. effect = subMesh.effect;
  77592. }
  77593. else {
  77594. effect = material.getEffect();
  77595. }
  77596. }
  77597. engine.enableEffect(effect);
  77598. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77599. if (mesh === _this.mesh) {
  77600. material.bind(mesh.getWorldMatrix(), mesh);
  77601. }
  77602. else {
  77603. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77604. // Alpha test
  77605. if (material && material.needAlphaTesting()) {
  77606. var alphaTexture = material.getAlphaTestTexture();
  77607. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77608. if (alphaTexture) {
  77609. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77610. }
  77611. }
  77612. // Bones
  77613. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77614. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77615. }
  77616. }
  77617. // Draw
  77618. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77619. }
  77620. };
  77621. // Render target texture callbacks
  77622. var savedSceneClearColor;
  77623. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77624. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77625. savedSceneClearColor = scene.clearColor;
  77626. scene.clearColor = sceneClearColor;
  77627. });
  77628. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77629. scene.clearColor = savedSceneClearColor;
  77630. });
  77631. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77632. var engine = scene.getEngine();
  77633. var index;
  77634. if (depthOnlySubMeshes.length) {
  77635. engine.setColorWrite(false);
  77636. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77637. renderSubMesh(depthOnlySubMeshes.data[index]);
  77638. }
  77639. engine.setColorWrite(true);
  77640. }
  77641. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77642. renderSubMesh(opaqueSubMeshes.data[index]);
  77643. }
  77644. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77645. renderSubMesh(alphaTestSubMeshes.data[index]);
  77646. }
  77647. if (transparentSubMeshes.length) {
  77648. // Sort sub meshes
  77649. for (index = 0; index < transparentSubMeshes.length; index++) {
  77650. var submesh = transparentSubMeshes.data[index];
  77651. var boundingInfo = submesh.getBoundingInfo();
  77652. if (boundingInfo && scene.activeCamera) {
  77653. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77654. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77655. }
  77656. }
  77657. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77658. sortedArray.sort(function (a, b) {
  77659. // Alpha index first
  77660. if (a._alphaIndex > b._alphaIndex) {
  77661. return 1;
  77662. }
  77663. if (a._alphaIndex < b._alphaIndex) {
  77664. return -1;
  77665. }
  77666. // Then distance to camera
  77667. if (a._distanceToCamera < b._distanceToCamera) {
  77668. return 1;
  77669. }
  77670. if (a._distanceToCamera > b._distanceToCamera) {
  77671. return -1;
  77672. }
  77673. return 0;
  77674. });
  77675. // Render sub meshes
  77676. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77677. for (index = 0; index < sortedArray.length; index++) {
  77678. renderSubMesh(sortedArray[index]);
  77679. }
  77680. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77681. }
  77682. };
  77683. };
  77684. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77685. var transform = scene.getTransformMatrix();
  77686. var meshPosition;
  77687. if (this.useCustomMeshPosition) {
  77688. meshPosition = this.customMeshPosition;
  77689. }
  77690. else if (this.attachedNode) {
  77691. meshPosition = this.attachedNode.position;
  77692. }
  77693. else {
  77694. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77695. }
  77696. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77697. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77698. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77699. if (this.invert)
  77700. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77701. };
  77702. // Static methods
  77703. /**
  77704. * Creates a default mesh for the Volumeric Light Scattering post-process
  77705. * @param {string} The mesh name
  77706. * @param {BABYLON.Scene} The scene where to create the mesh
  77707. * @return {BABYLON.Mesh} the default mesh
  77708. */
  77709. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77710. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77711. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77712. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77713. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77714. mesh.material = material;
  77715. return mesh;
  77716. };
  77717. __decorate([
  77718. BABYLON.serializeAsVector3()
  77719. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77720. __decorate([
  77721. BABYLON.serialize()
  77722. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77723. __decorate([
  77724. BABYLON.serialize()
  77725. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77726. __decorate([
  77727. BABYLON.serializeAsMeshReference()
  77728. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77729. __decorate([
  77730. BABYLON.serialize()
  77731. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77732. __decorate([
  77733. BABYLON.serialize()
  77734. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77735. __decorate([
  77736. BABYLON.serialize()
  77737. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77738. __decorate([
  77739. BABYLON.serialize()
  77740. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77741. __decorate([
  77742. BABYLON.serialize()
  77743. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77744. return VolumetricLightScatteringPostProcess;
  77745. }(BABYLON.PostProcess));
  77746. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77747. })(BABYLON || (BABYLON = {}));
  77748. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77749. //
  77750. // This post-process allows the modification of rendered colors by using
  77751. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77752. //
  77753. // The object needs to be provided an url to a texture containing the color
  77754. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77755. // Use an image editing software to tweak the LUT to match your needs.
  77756. //
  77757. // For an example of a color LUT, see here:
  77758. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77759. // For explanations on color grading, see here:
  77760. // http://udn.epicgames.com/Three/ColorGrading.html
  77761. //
  77762. var BABYLON;
  77763. (function (BABYLON) {
  77764. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77765. __extends(ColorCorrectionPostProcess, _super);
  77766. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77767. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77768. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77769. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77770. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77771. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77772. _this.onApply = function (effect) {
  77773. effect.setTexture("colorTable", _this._colorTableTexture);
  77774. };
  77775. return _this;
  77776. }
  77777. return ColorCorrectionPostProcess;
  77778. }(BABYLON.PostProcess));
  77779. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77780. })(BABYLON || (BABYLON = {}));
  77781. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77782. var BABYLON;
  77783. (function (BABYLON) {
  77784. /** Defines operator used for tonemapping */
  77785. var TonemappingOperator;
  77786. (function (TonemappingOperator) {
  77787. /** Hable */
  77788. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77789. /** Reinhard */
  77790. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77791. /** HejiDawson */
  77792. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77793. /** Photographic */
  77794. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77795. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77796. ;
  77797. /**
  77798. * Defines a post process to apply tone mapping
  77799. */
  77800. var TonemapPostProcess = /** @class */ (function (_super) {
  77801. __extends(TonemapPostProcess, _super);
  77802. /**
  77803. * Creates a new TonemapPostProcess
  77804. * @param name defines the name of the postprocess
  77805. * @param _operator defines the operator to use
  77806. * @param exposureAdjustment defines the required exposure adjustement
  77807. * @param camera defines the camera to use (can be null)
  77808. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77809. * @param engine defines the hosting engine (can be ignore if camera is set)
  77810. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77811. */
  77812. function TonemapPostProcess(name, _operator,
  77813. /** Defines the required exposure adjustement */
  77814. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77816. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77817. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77818. _this._operator = _operator;
  77819. _this.exposureAdjustment = exposureAdjustment;
  77820. var defines = "#define ";
  77821. if (_this._operator === TonemappingOperator.Hable)
  77822. defines += "HABLE_TONEMAPPING";
  77823. else if (_this._operator === TonemappingOperator.Reinhard)
  77824. defines += "REINHARD_TONEMAPPING";
  77825. else if (_this._operator === TonemappingOperator.HejiDawson)
  77826. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77827. else if (_this._operator === TonemappingOperator.Photographic)
  77828. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77829. //sadly a second call to create the effect.
  77830. _this.updateEffect(defines);
  77831. _this.onApply = function (effect) {
  77832. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77833. };
  77834. return _this;
  77835. }
  77836. return TonemapPostProcess;
  77837. }(BABYLON.PostProcess));
  77838. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77839. })(BABYLON || (BABYLON = {}));
  77840. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77841. var BABYLON;
  77842. (function (BABYLON) {
  77843. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77844. __extends(DisplayPassPostProcess, _super);
  77845. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77846. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77847. }
  77848. return DisplayPassPostProcess;
  77849. }(BABYLON.PostProcess));
  77850. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77851. })(BABYLON || (BABYLON = {}));
  77852. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77853. var BABYLON;
  77854. (function (BABYLON) {
  77855. var HighlightsPostProcess = /** @class */ (function (_super) {
  77856. __extends(HighlightsPostProcess, _super);
  77857. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77858. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77859. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77860. }
  77861. return HighlightsPostProcess;
  77862. }(BABYLON.PostProcess));
  77863. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77864. })(BABYLON || (BABYLON = {}));
  77865. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77866. var BABYLON;
  77867. (function (BABYLON) {
  77868. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77869. __extends(ImageProcessingPostProcess, _super);
  77870. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77871. if (camera === void 0) { camera = null; }
  77872. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77873. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77874. _this._fromLinearSpace = true;
  77875. /**
  77876. * Defines cache preventing GC.
  77877. */
  77878. _this._defines = {
  77879. IMAGEPROCESSING: false,
  77880. VIGNETTE: false,
  77881. VIGNETTEBLENDMODEMULTIPLY: false,
  77882. VIGNETTEBLENDMODEOPAQUE: false,
  77883. TONEMAPPING: false,
  77884. CONTRAST: false,
  77885. COLORCURVES: false,
  77886. COLORGRADING: false,
  77887. COLORGRADING3D: false,
  77888. FROMLINEARSPACE: false,
  77889. SAMPLER3DGREENDEPTH: false,
  77890. SAMPLER3DBGRMAP: false,
  77891. IMAGEPROCESSINGPOSTPROCESS: false,
  77892. EXPOSURE: false,
  77893. };
  77894. // Setup the configuration as forced by the constructor. This would then not force the
  77895. // scene materials output in linear space and let untouched the default forward pass.
  77896. if (imageProcessingConfiguration) {
  77897. imageProcessingConfiguration.applyByPostProcess = true;
  77898. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77899. // This will cause the shader to be compiled
  77900. _this.fromLinearSpace = false;
  77901. }
  77902. // Setup the default processing configuration to the scene.
  77903. else {
  77904. _this._attachImageProcessingConfiguration(null, true);
  77905. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77906. }
  77907. _this.onApply = function (effect) {
  77908. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77909. };
  77910. return _this;
  77911. }
  77912. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77913. /**
  77914. * Gets the image processing configuration used either in this material.
  77915. */
  77916. get: function () {
  77917. return this._imageProcessingConfiguration;
  77918. },
  77919. /**
  77920. * Sets the Default image processing configuration used either in the this material.
  77921. *
  77922. * If sets to null, the scene one is in use.
  77923. */
  77924. set: function (value) {
  77925. this._attachImageProcessingConfiguration(value);
  77926. },
  77927. enumerable: true,
  77928. configurable: true
  77929. });
  77930. /**
  77931. * Attaches a new image processing configuration to the PBR Material.
  77932. * @param configuration
  77933. */
  77934. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77935. var _this = this;
  77936. if (doNotBuild === void 0) { doNotBuild = false; }
  77937. if (configuration === this._imageProcessingConfiguration) {
  77938. return;
  77939. }
  77940. // Detaches observer.
  77941. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77942. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77943. }
  77944. // Pick the scene configuration if needed.
  77945. if (!configuration) {
  77946. var scene = null;
  77947. var engine = this.getEngine();
  77948. var camera = this.getCamera();
  77949. if (camera) {
  77950. scene = camera.getScene();
  77951. }
  77952. else if (engine && engine.scenes) {
  77953. var scenes = engine.scenes;
  77954. scene = scenes[scenes.length - 1];
  77955. }
  77956. else {
  77957. scene = BABYLON.Engine.LastCreatedScene;
  77958. }
  77959. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77960. }
  77961. else {
  77962. this._imageProcessingConfiguration = configuration;
  77963. }
  77964. // Attaches observer.
  77965. if (this._imageProcessingConfiguration) {
  77966. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77967. _this._updateParameters();
  77968. });
  77969. }
  77970. // Ensure the effect will be rebuilt.
  77971. if (!doNotBuild) {
  77972. this._updateParameters();
  77973. }
  77974. };
  77975. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77976. /**
  77977. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77978. */
  77979. get: function () {
  77980. return this.imageProcessingConfiguration.colorCurves;
  77981. },
  77982. /**
  77983. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77984. */
  77985. set: function (value) {
  77986. this.imageProcessingConfiguration.colorCurves = value;
  77987. },
  77988. enumerable: true,
  77989. configurable: true
  77990. });
  77991. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77992. /**
  77993. * Gets wether the color curves effect is enabled.
  77994. */
  77995. get: function () {
  77996. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77997. },
  77998. /**
  77999. * Sets wether the color curves effect is enabled.
  78000. */
  78001. set: function (value) {
  78002. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78003. },
  78004. enumerable: true,
  78005. configurable: true
  78006. });
  78007. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78008. /**
  78009. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78010. */
  78011. get: function () {
  78012. return this.imageProcessingConfiguration.colorGradingTexture;
  78013. },
  78014. /**
  78015. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78016. */
  78017. set: function (value) {
  78018. this.imageProcessingConfiguration.colorGradingTexture = value;
  78019. },
  78020. enumerable: true,
  78021. configurable: true
  78022. });
  78023. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78024. /**
  78025. * Gets wether the color grading effect is enabled.
  78026. */
  78027. get: function () {
  78028. return this.imageProcessingConfiguration.colorGradingEnabled;
  78029. },
  78030. /**
  78031. * Gets wether the color grading effect is enabled.
  78032. */
  78033. set: function (value) {
  78034. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78035. },
  78036. enumerable: true,
  78037. configurable: true
  78038. });
  78039. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78040. /**
  78041. * Gets exposure used in the effect.
  78042. */
  78043. get: function () {
  78044. return this.imageProcessingConfiguration.exposure;
  78045. },
  78046. /**
  78047. * Sets exposure used in the effect.
  78048. */
  78049. set: function (value) {
  78050. this.imageProcessingConfiguration.exposure = value;
  78051. },
  78052. enumerable: true,
  78053. configurable: true
  78054. });
  78055. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78056. /**
  78057. * Gets wether tonemapping is enabled or not.
  78058. */
  78059. get: function () {
  78060. return this._imageProcessingConfiguration.toneMappingEnabled;
  78061. },
  78062. /**
  78063. * Sets wether tonemapping is enabled or not
  78064. */
  78065. set: function (value) {
  78066. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78067. },
  78068. enumerable: true,
  78069. configurable: true
  78070. });
  78071. ;
  78072. ;
  78073. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78074. /**
  78075. * Gets contrast used in the effect.
  78076. */
  78077. get: function () {
  78078. return this.imageProcessingConfiguration.contrast;
  78079. },
  78080. /**
  78081. * Sets contrast used in the effect.
  78082. */
  78083. set: function (value) {
  78084. this.imageProcessingConfiguration.contrast = value;
  78085. },
  78086. enumerable: true,
  78087. configurable: true
  78088. });
  78089. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78090. /**
  78091. * Gets Vignette stretch size.
  78092. */
  78093. get: function () {
  78094. return this.imageProcessingConfiguration.vignetteStretch;
  78095. },
  78096. /**
  78097. * Sets Vignette stretch size.
  78098. */
  78099. set: function (value) {
  78100. this.imageProcessingConfiguration.vignetteStretch = value;
  78101. },
  78102. enumerable: true,
  78103. configurable: true
  78104. });
  78105. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78106. /**
  78107. * Gets Vignette centre X Offset.
  78108. */
  78109. get: function () {
  78110. return this.imageProcessingConfiguration.vignetteCentreX;
  78111. },
  78112. /**
  78113. * Sets Vignette centre X Offset.
  78114. */
  78115. set: function (value) {
  78116. this.imageProcessingConfiguration.vignetteCentreX = value;
  78117. },
  78118. enumerable: true,
  78119. configurable: true
  78120. });
  78121. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78122. /**
  78123. * Gets Vignette centre Y Offset.
  78124. */
  78125. get: function () {
  78126. return this.imageProcessingConfiguration.vignetteCentreY;
  78127. },
  78128. /**
  78129. * Sets Vignette centre Y Offset.
  78130. */
  78131. set: function (value) {
  78132. this.imageProcessingConfiguration.vignetteCentreY = value;
  78133. },
  78134. enumerable: true,
  78135. configurable: true
  78136. });
  78137. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78138. /**
  78139. * Gets Vignette weight or intensity of the vignette effect.
  78140. */
  78141. get: function () {
  78142. return this.imageProcessingConfiguration.vignetteWeight;
  78143. },
  78144. /**
  78145. * Sets Vignette weight or intensity of the vignette effect.
  78146. */
  78147. set: function (value) {
  78148. this.imageProcessingConfiguration.vignetteWeight = value;
  78149. },
  78150. enumerable: true,
  78151. configurable: true
  78152. });
  78153. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78154. /**
  78155. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78156. * if vignetteEnabled is set to true.
  78157. */
  78158. get: function () {
  78159. return this.imageProcessingConfiguration.vignetteColor;
  78160. },
  78161. /**
  78162. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78163. * if vignetteEnabled is set to true.
  78164. */
  78165. set: function (value) {
  78166. this.imageProcessingConfiguration.vignetteColor = value;
  78167. },
  78168. enumerable: true,
  78169. configurable: true
  78170. });
  78171. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78172. /**
  78173. * Gets Camera field of view used by the Vignette effect.
  78174. */
  78175. get: function () {
  78176. return this.imageProcessingConfiguration.vignetteCameraFov;
  78177. },
  78178. /**
  78179. * Sets Camera field of view used by the Vignette effect.
  78180. */
  78181. set: function (value) {
  78182. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78183. },
  78184. enumerable: true,
  78185. configurable: true
  78186. });
  78187. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78188. /**
  78189. * Gets the vignette blend mode allowing different kind of effect.
  78190. */
  78191. get: function () {
  78192. return this.imageProcessingConfiguration.vignetteBlendMode;
  78193. },
  78194. /**
  78195. * Sets the vignette blend mode allowing different kind of effect.
  78196. */
  78197. set: function (value) {
  78198. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78199. },
  78200. enumerable: true,
  78201. configurable: true
  78202. });
  78203. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78204. /**
  78205. * Gets wether the vignette effect is enabled.
  78206. */
  78207. get: function () {
  78208. return this.imageProcessingConfiguration.vignetteEnabled;
  78209. },
  78210. /**
  78211. * Sets wether the vignette effect is enabled.
  78212. */
  78213. set: function (value) {
  78214. this.imageProcessingConfiguration.vignetteEnabled = value;
  78215. },
  78216. enumerable: true,
  78217. configurable: true
  78218. });
  78219. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78220. /**
  78221. * Gets wether the input of the processing is in Gamma or Linear Space.
  78222. */
  78223. get: function () {
  78224. return this._fromLinearSpace;
  78225. },
  78226. /**
  78227. * Sets wether the input of the processing is in Gamma or Linear Space.
  78228. */
  78229. set: function (value) {
  78230. if (this._fromLinearSpace === value) {
  78231. return;
  78232. }
  78233. this._fromLinearSpace = value;
  78234. this._updateParameters();
  78235. },
  78236. enumerable: true,
  78237. configurable: true
  78238. });
  78239. ImageProcessingPostProcess.prototype.getClassName = function () {
  78240. return "ImageProcessingPostProcess";
  78241. };
  78242. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78243. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78244. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78245. var defines = "";
  78246. for (var define in this._defines) {
  78247. if (this._defines[define]) {
  78248. defines += "#define " + define + ";\r\n";
  78249. }
  78250. }
  78251. var samplers = ["textureSampler"];
  78252. var uniforms = ["scale"];
  78253. if (BABYLON.ImageProcessingConfiguration) {
  78254. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78255. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78256. }
  78257. this.updateEffect(defines, uniforms, samplers);
  78258. };
  78259. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78260. _super.prototype.dispose.call(this, camera);
  78261. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78262. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78263. }
  78264. if (this._imageProcessingConfiguration) {
  78265. this.imageProcessingConfiguration.applyByPostProcess = false;
  78266. }
  78267. };
  78268. __decorate([
  78269. BABYLON.serialize()
  78270. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78271. return ImageProcessingPostProcess;
  78272. }(BABYLON.PostProcess));
  78273. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78274. })(BABYLON || (BABYLON = {}));
  78275. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78276. var BABYLON;
  78277. (function (BABYLON) {
  78278. /**
  78279. * Class used to store bone information
  78280. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78281. */
  78282. var Bone = /** @class */ (function (_super) {
  78283. __extends(Bone, _super);
  78284. /**
  78285. * Create a new bone
  78286. * @param name defines the bone name
  78287. * @param skeleton defines the parent skeleton
  78288. * @param parentBone defines the parent (can be null if the bone is the root)
  78289. * @param localMatrix defines the local matrix
  78290. * @param restPose defines the rest pose matrix
  78291. * @param baseMatrix defines the base matrix
  78292. * @param index defines index of the bone in the hiearchy
  78293. */
  78294. function Bone(
  78295. /**
  78296. * defines the bone name
  78297. */
  78298. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78299. if (parentBone === void 0) { parentBone = null; }
  78300. if (localMatrix === void 0) { localMatrix = null; }
  78301. if (restPose === void 0) { restPose = null; }
  78302. if (baseMatrix === void 0) { baseMatrix = null; }
  78303. if (index === void 0) { index = null; }
  78304. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78305. _this.name = name;
  78306. /**
  78307. * Gets the list of child bones
  78308. */
  78309. _this.children = new Array();
  78310. /** Gets the animations associated with this bone */
  78311. _this.animations = new Array();
  78312. /**
  78313. * @hidden Internal only
  78314. * Set this value to map this bone to a different index in the transform matrices
  78315. * Set this value to -1 to exclude the bone from the transform matrices
  78316. */
  78317. _this._index = null;
  78318. _this._absoluteTransform = new BABYLON.Matrix();
  78319. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78320. _this._scalingDeterminant = 1;
  78321. _this._worldTransform = new BABYLON.Matrix();
  78322. _this._needToDecompose = true;
  78323. _this._needToCompose = false;
  78324. _this._skeleton = skeleton;
  78325. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78326. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78327. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78328. _this._index = index;
  78329. skeleton.bones.push(_this);
  78330. _this.setParent(parentBone, false);
  78331. if (baseMatrix || localMatrix) {
  78332. _this._updateDifferenceMatrix();
  78333. }
  78334. return _this;
  78335. }
  78336. Object.defineProperty(Bone.prototype, "_matrix", {
  78337. /** @hidden */
  78338. get: function () {
  78339. this._compose();
  78340. return this._localMatrix;
  78341. },
  78342. /** @hidden */
  78343. set: function (value) {
  78344. this._localMatrix.copyFrom(value);
  78345. this._needToDecompose = true;
  78346. },
  78347. enumerable: true,
  78348. configurable: true
  78349. });
  78350. // Members
  78351. /**
  78352. * Gets the parent skeleton
  78353. * @returns a skeleton
  78354. */
  78355. Bone.prototype.getSkeleton = function () {
  78356. return this._skeleton;
  78357. };
  78358. /**
  78359. * Gets parent bone
  78360. * @returns a bone or null if the bone is the root of the bone hierarchy
  78361. */
  78362. Bone.prototype.getParent = function () {
  78363. return this._parent;
  78364. };
  78365. /**
  78366. * Sets the parent bone
  78367. * @param parent defines the parent (can be null if the bone is the root)
  78368. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78369. */
  78370. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78371. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78372. if (this._parent === parent) {
  78373. return;
  78374. }
  78375. if (this._parent) {
  78376. var index = this._parent.children.indexOf(this);
  78377. if (index !== -1) {
  78378. this._parent.children.splice(index, 1);
  78379. }
  78380. }
  78381. this._parent = parent;
  78382. if (this._parent) {
  78383. this._parent.children.push(this);
  78384. }
  78385. if (updateDifferenceMatrix) {
  78386. this._updateDifferenceMatrix();
  78387. }
  78388. this.markAsDirty();
  78389. };
  78390. /**
  78391. * Gets the local matrix
  78392. * @returns a matrix
  78393. */
  78394. Bone.prototype.getLocalMatrix = function () {
  78395. this._compose();
  78396. return this._localMatrix;
  78397. };
  78398. /**
  78399. * Gets the base matrix (initial matrix which remains unchanged)
  78400. * @returns a matrix
  78401. */
  78402. Bone.prototype.getBaseMatrix = function () {
  78403. return this._baseMatrix;
  78404. };
  78405. /**
  78406. * Gets the rest pose matrix
  78407. * @returns a matrix
  78408. */
  78409. Bone.prototype.getRestPose = function () {
  78410. return this._restPose;
  78411. };
  78412. /**
  78413. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78414. */
  78415. Bone.prototype.getWorldMatrix = function () {
  78416. return this._worldTransform;
  78417. };
  78418. /**
  78419. * Sets the local matrix to rest pose matrix
  78420. */
  78421. Bone.prototype.returnToRest = function () {
  78422. this.updateMatrix(this._restPose.clone());
  78423. };
  78424. /**
  78425. * Gets the inverse of the absolute transform matrix.
  78426. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78427. * @returns a matrix
  78428. */
  78429. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78430. return this._invertedAbsoluteTransform;
  78431. };
  78432. /**
  78433. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78434. * @returns a matrix
  78435. */
  78436. Bone.prototype.getAbsoluteTransform = function () {
  78437. return this._absoluteTransform;
  78438. };
  78439. Object.defineProperty(Bone.prototype, "position", {
  78440. // Properties (matches AbstractMesh properties)
  78441. /** Gets or sets current position (in local space) */
  78442. get: function () {
  78443. this._decompose();
  78444. return this._localPosition;
  78445. },
  78446. set: function (newPosition) {
  78447. this._decompose();
  78448. this._localPosition.copyFrom(newPosition);
  78449. this._markAsDirtyAndCompose();
  78450. },
  78451. enumerable: true,
  78452. configurable: true
  78453. });
  78454. Object.defineProperty(Bone.prototype, "rotation", {
  78455. /** Gets or sets current rotation (in local space) */
  78456. get: function () {
  78457. return this.getRotation();
  78458. },
  78459. set: function (newRotation) {
  78460. this.setRotation(newRotation);
  78461. },
  78462. enumerable: true,
  78463. configurable: true
  78464. });
  78465. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78466. /** Gets or sets current rotation quaternion (in local space) */
  78467. get: function () {
  78468. this._decompose();
  78469. return this._localRotation;
  78470. },
  78471. set: function (newRotation) {
  78472. this.setRotationQuaternion(newRotation);
  78473. },
  78474. enumerable: true,
  78475. configurable: true
  78476. });
  78477. Object.defineProperty(Bone.prototype, "scaling", {
  78478. /** Gets or sets current scaling (in local space) */
  78479. get: function () {
  78480. return this.getScale();
  78481. },
  78482. set: function (newScaling) {
  78483. this.setScale(newScaling);
  78484. },
  78485. enumerable: true,
  78486. configurable: true
  78487. });
  78488. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78489. /**
  78490. * Gets the animation properties override
  78491. */
  78492. get: function () {
  78493. return this._skeleton.animationPropertiesOverride;
  78494. },
  78495. enumerable: true,
  78496. configurable: true
  78497. });
  78498. // Methods
  78499. Bone.prototype._decompose = function () {
  78500. if (!this._needToDecompose) {
  78501. return;
  78502. }
  78503. this._needToDecompose = false;
  78504. if (!this._localScaling) {
  78505. this._localScaling = BABYLON.Vector3.Zero();
  78506. this._localRotation = BABYLON.Quaternion.Zero();
  78507. this._localPosition = BABYLON.Vector3.Zero();
  78508. }
  78509. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78510. };
  78511. Bone.prototype._compose = function () {
  78512. if (!this._needToCompose) {
  78513. return;
  78514. }
  78515. this._needToCompose = false;
  78516. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78517. };
  78518. /**
  78519. * Update the base and local matrices
  78520. * @param matrix defines the new base or local matrix
  78521. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78522. * @param updateLocalMatrix defines if the local matrix should be updated
  78523. */
  78524. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78525. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78526. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78527. this._baseMatrix.copyFrom(matrix);
  78528. if (updateDifferenceMatrix) {
  78529. this._updateDifferenceMatrix();
  78530. }
  78531. if (updateLocalMatrix) {
  78532. this._localMatrix.copyFrom(matrix);
  78533. this._markAsDirtyAndDecompose();
  78534. }
  78535. else {
  78536. this.markAsDirty();
  78537. }
  78538. };
  78539. /** @hidden */
  78540. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78541. if (updateChildren === void 0) { updateChildren = true; }
  78542. if (!rootMatrix) {
  78543. rootMatrix = this._baseMatrix;
  78544. }
  78545. if (this._parent) {
  78546. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78547. }
  78548. else {
  78549. this._absoluteTransform.copyFrom(rootMatrix);
  78550. }
  78551. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78552. if (updateChildren) {
  78553. for (var index = 0; index < this.children.length; index++) {
  78554. this.children[index]._updateDifferenceMatrix();
  78555. }
  78556. }
  78557. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78558. };
  78559. /**
  78560. * Flag the bone as dirty (Forcing it to update everything)
  78561. */
  78562. Bone.prototype.markAsDirty = function () {
  78563. this._currentRenderId++;
  78564. this._childRenderId++;
  78565. this._skeleton._markAsDirty();
  78566. };
  78567. Bone.prototype._markAsDirtyAndCompose = function () {
  78568. this.markAsDirty();
  78569. this._needToCompose = true;
  78570. };
  78571. Bone.prototype._markAsDirtyAndDecompose = function () {
  78572. this.markAsDirty();
  78573. this._needToDecompose = true;
  78574. };
  78575. /**
  78576. * Copy an animation range from another bone
  78577. * @param source defines the source bone
  78578. * @param rangeName defines the range name to copy
  78579. * @param frameOffset defines the frame offset
  78580. * @param rescaleAsRequired defines if rescaling must be applied if required
  78581. * @param skelDimensionsRatio defines the scaling ratio
  78582. * @returns true if operation was successful
  78583. */
  78584. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78585. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78586. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78587. // all animation may be coming from a library skeleton, so may need to create animation
  78588. if (this.animations.length === 0) {
  78589. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78590. this.animations[0].setKeys([]);
  78591. }
  78592. // get animation info / verify there is such a range from the source bone
  78593. var sourceRange = source.animations[0].getRange(rangeName);
  78594. if (!sourceRange) {
  78595. return false;
  78596. }
  78597. var from = sourceRange.from;
  78598. var to = sourceRange.to;
  78599. var sourceKeys = source.animations[0].getKeys();
  78600. // rescaling prep
  78601. var sourceBoneLength = source.length;
  78602. var sourceParent = source.getParent();
  78603. var parent = this.getParent();
  78604. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78605. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78606. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78607. var destKeys = this.animations[0].getKeys();
  78608. // loop vars declaration
  78609. var orig;
  78610. var origTranslation;
  78611. var mat;
  78612. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78613. orig = sourceKeys[key];
  78614. if (orig.frame >= from && orig.frame <= to) {
  78615. if (rescaleAsRequired) {
  78616. mat = orig.value.clone();
  78617. // scale based on parent ratio, when bone has parent
  78618. if (parentScalingReqd) {
  78619. origTranslation = mat.getTranslation();
  78620. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78621. // scale based on skeleton dimension ratio when root bone, and value is passed
  78622. }
  78623. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78624. origTranslation = mat.getTranslation();
  78625. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78626. // use original when root bone, and no data for skelDimensionsRatio
  78627. }
  78628. else {
  78629. mat = orig.value;
  78630. }
  78631. }
  78632. else {
  78633. mat = orig.value;
  78634. }
  78635. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78636. }
  78637. }
  78638. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78639. return true;
  78640. };
  78641. /**
  78642. * Translate the bone in local or world space
  78643. * @param vec The amount to translate the bone
  78644. * @param space The space that the translation is in
  78645. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78646. */
  78647. Bone.prototype.translate = function (vec, space, mesh) {
  78648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78649. var lm = this.getLocalMatrix();
  78650. if (space == BABYLON.Space.LOCAL) {
  78651. lm.m[12] += vec.x;
  78652. lm.m[13] += vec.y;
  78653. lm.m[14] += vec.z;
  78654. }
  78655. else {
  78656. var wm = null;
  78657. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78658. if (mesh) {
  78659. wm = mesh.getWorldMatrix();
  78660. }
  78661. this._skeleton.computeAbsoluteTransforms();
  78662. var tmat = Bone._tmpMats[0];
  78663. var tvec = Bone._tmpVecs[0];
  78664. if (this._parent) {
  78665. if (mesh && wm) {
  78666. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78667. tmat.multiplyToRef(wm, tmat);
  78668. }
  78669. else {
  78670. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78671. }
  78672. }
  78673. tmat.m[12] = 0;
  78674. tmat.m[13] = 0;
  78675. tmat.m[14] = 0;
  78676. tmat.invert();
  78677. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78678. lm.m[12] += tvec.x;
  78679. lm.m[13] += tvec.y;
  78680. lm.m[14] += tvec.z;
  78681. }
  78682. this._markAsDirtyAndDecompose();
  78683. };
  78684. /**
  78685. * Set the postion of the bone in local or world space
  78686. * @param position The position to set the bone
  78687. * @param space The space that the position is in
  78688. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78689. */
  78690. Bone.prototype.setPosition = function (position, space, mesh) {
  78691. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78692. var lm = this.getLocalMatrix();
  78693. if (space == BABYLON.Space.LOCAL) {
  78694. lm.m[12] = position.x;
  78695. lm.m[13] = position.y;
  78696. lm.m[14] = position.z;
  78697. }
  78698. else {
  78699. var wm = null;
  78700. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78701. if (mesh) {
  78702. wm = mesh.getWorldMatrix();
  78703. }
  78704. this._skeleton.computeAbsoluteTransforms();
  78705. var tmat = Bone._tmpMats[0];
  78706. var vec = Bone._tmpVecs[0];
  78707. if (this._parent) {
  78708. if (mesh && wm) {
  78709. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78710. tmat.multiplyToRef(wm, tmat);
  78711. }
  78712. else {
  78713. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78714. }
  78715. }
  78716. tmat.invert();
  78717. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78718. lm.m[12] = vec.x;
  78719. lm.m[13] = vec.y;
  78720. lm.m[14] = vec.z;
  78721. }
  78722. this._markAsDirtyAndDecompose();
  78723. };
  78724. /**
  78725. * Set the absolute position of the bone (world space)
  78726. * @param position The position to set the bone
  78727. * @param mesh The mesh that this bone is attached to
  78728. */
  78729. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78730. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78731. };
  78732. /**
  78733. * Scale the bone on the x, y and z axes (in local space)
  78734. * @param x The amount to scale the bone on the x axis
  78735. * @param y The amount to scale the bone on the y axis
  78736. * @param z The amount to scale the bone on the z axis
  78737. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78738. */
  78739. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78740. if (scaleChildren === void 0) { scaleChildren = false; }
  78741. var locMat = this.getLocalMatrix();
  78742. // Apply new scaling on top of current local matrix
  78743. var scaleMat = Bone._tmpMats[0];
  78744. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78745. scaleMat.multiplyToRef(locMat, locMat);
  78746. // Invert scaling matrix and apply the inverse to all children
  78747. scaleMat.invert();
  78748. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78749. var child = _a[_i];
  78750. var cm = child.getLocalMatrix();
  78751. cm.multiplyToRef(scaleMat, cm);
  78752. cm.m[12] *= x;
  78753. cm.m[13] *= y;
  78754. cm.m[14] *= z;
  78755. child._markAsDirtyAndDecompose();
  78756. }
  78757. this._markAsDirtyAndDecompose();
  78758. if (scaleChildren) {
  78759. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78760. var child = _c[_b];
  78761. child.scale(x, y, z, scaleChildren);
  78762. }
  78763. }
  78764. };
  78765. /**
  78766. * Set the bone scaling in local space
  78767. * @param scale defines the scaling vector
  78768. */
  78769. Bone.prototype.setScale = function (scale) {
  78770. this._decompose();
  78771. this._localScaling.copyFrom(scale);
  78772. this._markAsDirtyAndCompose();
  78773. };
  78774. /**
  78775. * Gets the current scaling in local space
  78776. * @returns the current scaling vector
  78777. */
  78778. Bone.prototype.getScale = function () {
  78779. this._decompose();
  78780. return this._localScaling;
  78781. };
  78782. /**
  78783. * Gets the current scaling in local space and stores it in a target vector
  78784. * @param result defines the target vector
  78785. */
  78786. Bone.prototype.getScaleToRef = function (result) {
  78787. this._decompose();
  78788. result.copyFrom(this._localScaling);
  78789. };
  78790. /**
  78791. * Set the yaw, pitch, and roll of the bone in local or world space
  78792. * @param yaw The rotation of the bone on the y axis
  78793. * @param pitch The rotation of the bone on the x axis
  78794. * @param roll The rotation of the bone on the z axis
  78795. * @param space The space that the axes of rotation are in
  78796. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78797. */
  78798. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78799. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78800. if (space === BABYLON.Space.LOCAL) {
  78801. var quat = Bone._tmpQuat;
  78802. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78803. this.setRotationQuaternion(quat, space, mesh);
  78804. return;
  78805. }
  78806. var rotMatInv = Bone._tmpMats[0];
  78807. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78808. return;
  78809. }
  78810. var rotMat = Bone._tmpMats[1];
  78811. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78812. rotMatInv.multiplyToRef(rotMat, rotMat);
  78813. this._rotateWithMatrix(rotMat, space, mesh);
  78814. };
  78815. /**
  78816. * Add a rotation to the bone on an axis in local or world space
  78817. * @param axis The axis to rotate the bone on
  78818. * @param amount The amount to rotate the bone
  78819. * @param space The space that the axis is in
  78820. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78821. */
  78822. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78823. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78824. var rmat = Bone._tmpMats[0];
  78825. rmat.m[12] = 0;
  78826. rmat.m[13] = 0;
  78827. rmat.m[14] = 0;
  78828. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78829. this._rotateWithMatrix(rmat, space, mesh);
  78830. };
  78831. /**
  78832. * Set the rotation of the bone to a particular axis angle in local or world space
  78833. * @param axis The axis to rotate the bone on
  78834. * @param angle The angle that the bone should be rotated to
  78835. * @param space The space that the axis is in
  78836. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78837. */
  78838. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78839. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78840. if (space === BABYLON.Space.LOCAL) {
  78841. var quat = Bone._tmpQuat;
  78842. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78843. this.setRotationQuaternion(quat, space, mesh);
  78844. return;
  78845. }
  78846. var rotMatInv = Bone._tmpMats[0];
  78847. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78848. return;
  78849. }
  78850. var rotMat = Bone._tmpMats[1];
  78851. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78852. rotMatInv.multiplyToRef(rotMat, rotMat);
  78853. this._rotateWithMatrix(rotMat, space, mesh);
  78854. };
  78855. /**
  78856. * Set the euler rotation of the bone in local of world space
  78857. * @param rotation The euler rotation that the bone should be set to
  78858. * @param space The space that the rotation is in
  78859. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78860. */
  78861. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78862. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78863. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78864. };
  78865. /**
  78866. * Set the quaternion rotation of the bone in local of world space
  78867. * @param quat The quaternion rotation that the bone should be set to
  78868. * @param space The space that the rotation is in
  78869. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78870. */
  78871. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78872. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78873. if (space === BABYLON.Space.LOCAL) {
  78874. this._decompose();
  78875. this._localRotation.copyFrom(quat);
  78876. this._markAsDirtyAndCompose();
  78877. return;
  78878. }
  78879. var rotMatInv = Bone._tmpMats[0];
  78880. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78881. return;
  78882. }
  78883. var rotMat = Bone._tmpMats[1];
  78884. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78885. rotMatInv.multiplyToRef(rotMat, rotMat);
  78886. this._rotateWithMatrix(rotMat, space, mesh);
  78887. };
  78888. /**
  78889. * Set the rotation matrix of the bone in local of world space
  78890. * @param rotMat The rotation matrix that the bone should be set to
  78891. * @param space The space that the rotation is in
  78892. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78893. */
  78894. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78895. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78896. if (space === BABYLON.Space.LOCAL) {
  78897. var quat = Bone._tmpQuat;
  78898. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78899. this.setRotationQuaternion(quat, space, mesh);
  78900. return;
  78901. }
  78902. var rotMatInv = Bone._tmpMats[0];
  78903. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78904. return;
  78905. }
  78906. var rotMat2 = Bone._tmpMats[1];
  78907. rotMat2.copyFrom(rotMat);
  78908. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78909. this._rotateWithMatrix(rotMat2, space, mesh);
  78910. };
  78911. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78912. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78913. var lmat = this.getLocalMatrix();
  78914. var lx = lmat.m[12];
  78915. var ly = lmat.m[13];
  78916. var lz = lmat.m[14];
  78917. var parent = this.getParent();
  78918. var parentScale = Bone._tmpMats[3];
  78919. var parentScaleInv = Bone._tmpMats[4];
  78920. if (parent && space == BABYLON.Space.WORLD) {
  78921. if (mesh) {
  78922. parentScale.copyFrom(mesh.getWorldMatrix());
  78923. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78924. }
  78925. else {
  78926. parentScale.copyFrom(parent.getAbsoluteTransform());
  78927. }
  78928. parentScaleInv.copyFrom(parentScale);
  78929. parentScaleInv.invert();
  78930. lmat.multiplyToRef(parentScale, lmat);
  78931. lmat.multiplyToRef(rmat, lmat);
  78932. lmat.multiplyToRef(parentScaleInv, lmat);
  78933. }
  78934. else {
  78935. if (space == BABYLON.Space.WORLD && mesh) {
  78936. parentScale.copyFrom(mesh.getWorldMatrix());
  78937. parentScaleInv.copyFrom(parentScale);
  78938. parentScaleInv.invert();
  78939. lmat.multiplyToRef(parentScale, lmat);
  78940. lmat.multiplyToRef(rmat, lmat);
  78941. lmat.multiplyToRef(parentScaleInv, lmat);
  78942. }
  78943. else {
  78944. lmat.multiplyToRef(rmat, lmat);
  78945. }
  78946. }
  78947. lmat.m[12] = lx;
  78948. lmat.m[13] = ly;
  78949. lmat.m[14] = lz;
  78950. this.computeAbsoluteTransforms();
  78951. this._markAsDirtyAndDecompose();
  78952. };
  78953. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78954. var scaleMatrix = Bone._tmpMats[2];
  78955. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78956. if (mesh) {
  78957. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78958. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78959. }
  78960. rotMatInv.invert();
  78961. if (isNaN(rotMatInv.m[0])) {
  78962. // Matrix failed to invert.
  78963. // This can happen if scale is zero for example.
  78964. return false;
  78965. }
  78966. scaleMatrix.m[0] *= this._scalingDeterminant;
  78967. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78968. return true;
  78969. };
  78970. /**
  78971. * Get the position of the bone in local or world space
  78972. * @param space The space that the returned position is in
  78973. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78974. * @returns The position of the bone
  78975. */
  78976. Bone.prototype.getPosition = function (space, mesh) {
  78977. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78978. if (mesh === void 0) { mesh = null; }
  78979. var pos = BABYLON.Vector3.Zero();
  78980. this.getPositionToRef(space, mesh, pos);
  78981. return pos;
  78982. };
  78983. /**
  78984. * Copy the position of the bone to a vector3 in local or world space
  78985. * @param space The space that the returned position is in
  78986. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78987. * @param result The vector3 to copy the position to
  78988. */
  78989. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78990. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78991. if (space == BABYLON.Space.LOCAL) {
  78992. var lm = this.getLocalMatrix();
  78993. result.x = lm.m[12];
  78994. result.y = lm.m[13];
  78995. result.z = lm.m[14];
  78996. }
  78997. else {
  78998. var wm = null;
  78999. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79000. if (mesh) {
  79001. wm = mesh.getWorldMatrix();
  79002. }
  79003. this._skeleton.computeAbsoluteTransforms();
  79004. var tmat = Bone._tmpMats[0];
  79005. if (mesh && wm) {
  79006. tmat.copyFrom(this.getAbsoluteTransform());
  79007. tmat.multiplyToRef(wm, tmat);
  79008. }
  79009. else {
  79010. tmat = this.getAbsoluteTransform();
  79011. }
  79012. result.x = tmat.m[12];
  79013. result.y = tmat.m[13];
  79014. result.z = tmat.m[14];
  79015. }
  79016. };
  79017. /**
  79018. * Get the absolute position of the bone (world space)
  79019. * @param mesh The mesh that this bone is attached to
  79020. * @returns The absolute position of the bone
  79021. */
  79022. Bone.prototype.getAbsolutePosition = function (mesh) {
  79023. if (mesh === void 0) { mesh = null; }
  79024. var pos = BABYLON.Vector3.Zero();
  79025. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79026. return pos;
  79027. };
  79028. /**
  79029. * Copy the absolute position of the bone (world space) to the result param
  79030. * @param mesh The mesh that this bone is attached to
  79031. * @param result The vector3 to copy the absolute position to
  79032. */
  79033. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79034. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79035. };
  79036. /**
  79037. * Compute the absolute transforms of this bone and its children
  79038. */
  79039. Bone.prototype.computeAbsoluteTransforms = function () {
  79040. this._compose();
  79041. if (this._parent) {
  79042. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79043. }
  79044. else {
  79045. this._absoluteTransform.copyFrom(this._localMatrix);
  79046. var poseMatrix = this._skeleton.getPoseMatrix();
  79047. if (poseMatrix) {
  79048. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79049. }
  79050. }
  79051. var children = this.children;
  79052. var len = children.length;
  79053. for (var i = 0; i < len; i++) {
  79054. children[i].computeAbsoluteTransforms();
  79055. }
  79056. };
  79057. /**
  79058. * Get the world direction from an axis that is in the local space of the bone
  79059. * @param localAxis The local direction that is used to compute the world direction
  79060. * @param mesh The mesh that this bone is attached to
  79061. * @returns The world direction
  79062. */
  79063. Bone.prototype.getDirection = function (localAxis, mesh) {
  79064. if (mesh === void 0) { mesh = null; }
  79065. var result = BABYLON.Vector3.Zero();
  79066. this.getDirectionToRef(localAxis, mesh, result);
  79067. return result;
  79068. };
  79069. /**
  79070. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79071. * @param localAxis The local direction that is used to compute the world direction
  79072. * @param mesh The mesh that this bone is attached to
  79073. * @param result The vector3 that the world direction will be copied to
  79074. */
  79075. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79076. if (mesh === void 0) { mesh = null; }
  79077. var wm = null;
  79078. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79079. if (mesh) {
  79080. wm = mesh.getWorldMatrix();
  79081. }
  79082. this._skeleton.computeAbsoluteTransforms();
  79083. var mat = Bone._tmpMats[0];
  79084. mat.copyFrom(this.getAbsoluteTransform());
  79085. if (mesh && wm) {
  79086. mat.multiplyToRef(wm, mat);
  79087. }
  79088. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79089. result.normalize();
  79090. };
  79091. /**
  79092. * Get the euler rotation of the bone in local or world space
  79093. * @param space The space that the rotation should be in
  79094. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79095. * @returns The euler rotation
  79096. */
  79097. Bone.prototype.getRotation = function (space, mesh) {
  79098. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79099. if (mesh === void 0) { mesh = null; }
  79100. var result = BABYLON.Vector3.Zero();
  79101. this.getRotationToRef(space, mesh, result);
  79102. return result;
  79103. };
  79104. /**
  79105. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79106. * @param space The space that the rotation should be in
  79107. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79108. * @param result The vector3 that the rotation should be copied to
  79109. */
  79110. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79111. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79112. if (mesh === void 0) { mesh = null; }
  79113. var quat = Bone._tmpQuat;
  79114. this.getRotationQuaternionToRef(space, mesh, quat);
  79115. quat.toEulerAnglesToRef(result);
  79116. };
  79117. /**
  79118. * Get the quaternion rotation of the bone in either local or world space
  79119. * @param space The space that the rotation should be in
  79120. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79121. * @returns The quaternion rotation
  79122. */
  79123. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79124. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79125. if (mesh === void 0) { mesh = null; }
  79126. var result = BABYLON.Quaternion.Identity();
  79127. this.getRotationQuaternionToRef(space, mesh, result);
  79128. return result;
  79129. };
  79130. /**
  79131. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79132. * @param space The space that the rotation should be in
  79133. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79134. * @param result The quaternion that the rotation should be copied to
  79135. */
  79136. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79137. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79138. if (mesh === void 0) { mesh = null; }
  79139. if (space == BABYLON.Space.LOCAL) {
  79140. this._decompose();
  79141. result.copyFrom(this._localRotation);
  79142. }
  79143. else {
  79144. var mat = Bone._tmpMats[0];
  79145. var amat = this.getAbsoluteTransform();
  79146. if (mesh) {
  79147. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79148. }
  79149. else {
  79150. mat.copyFrom(amat);
  79151. }
  79152. mat.m[0] *= this._scalingDeterminant;
  79153. mat.m[1] *= this._scalingDeterminant;
  79154. mat.m[2] *= this._scalingDeterminant;
  79155. mat.decompose(undefined, result, undefined);
  79156. }
  79157. };
  79158. /**
  79159. * Get the rotation matrix of the bone in local or world space
  79160. * @param space The space that the rotation should be in
  79161. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79162. * @returns The rotation matrix
  79163. */
  79164. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79165. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79166. var result = BABYLON.Matrix.Identity();
  79167. this.getRotationMatrixToRef(space, mesh, result);
  79168. return result;
  79169. };
  79170. /**
  79171. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79172. * @param space The space that the rotation should be in
  79173. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79174. * @param result The quaternion that the rotation should be copied to
  79175. */
  79176. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79177. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79178. if (space == BABYLON.Space.LOCAL) {
  79179. this.getLocalMatrix().getRotationMatrixToRef(result);
  79180. }
  79181. else {
  79182. var mat = Bone._tmpMats[0];
  79183. var amat = this.getAbsoluteTransform();
  79184. if (mesh) {
  79185. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79186. }
  79187. else {
  79188. mat.copyFrom(amat);
  79189. }
  79190. mat.m[0] *= this._scalingDeterminant;
  79191. mat.m[1] *= this._scalingDeterminant;
  79192. mat.m[2] *= this._scalingDeterminant;
  79193. mat.getRotationMatrixToRef(result);
  79194. }
  79195. };
  79196. /**
  79197. * Get the world position of a point that is in the local space of the bone
  79198. * @param position The local position
  79199. * @param mesh The mesh that this bone is attached to
  79200. * @returns The world position
  79201. */
  79202. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79203. if (mesh === void 0) { mesh = null; }
  79204. var result = BABYLON.Vector3.Zero();
  79205. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79206. return result;
  79207. };
  79208. /**
  79209. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79210. * @param position The local position
  79211. * @param mesh The mesh that this bone is attached to
  79212. * @param result The vector3 that the world position should be copied to
  79213. */
  79214. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79215. if (mesh === void 0) { mesh = null; }
  79216. var wm = null;
  79217. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79218. if (mesh) {
  79219. wm = mesh.getWorldMatrix();
  79220. }
  79221. this._skeleton.computeAbsoluteTransforms();
  79222. var tmat = Bone._tmpMats[0];
  79223. if (mesh && wm) {
  79224. tmat.copyFrom(this.getAbsoluteTransform());
  79225. tmat.multiplyToRef(wm, tmat);
  79226. }
  79227. else {
  79228. tmat = this.getAbsoluteTransform();
  79229. }
  79230. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79231. };
  79232. /**
  79233. * Get the local position of a point that is in world space
  79234. * @param position The world position
  79235. * @param mesh The mesh that this bone is attached to
  79236. * @returns The local position
  79237. */
  79238. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79239. if (mesh === void 0) { mesh = null; }
  79240. var result = BABYLON.Vector3.Zero();
  79241. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79242. return result;
  79243. };
  79244. /**
  79245. * Get the local position of a point that is in world space and copy it to the result param
  79246. * @param position The world position
  79247. * @param mesh The mesh that this bone is attached to
  79248. * @param result The vector3 that the local position should be copied to
  79249. */
  79250. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79251. if (mesh === void 0) { mesh = null; }
  79252. var wm = null;
  79253. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79254. if (mesh) {
  79255. wm = mesh.getWorldMatrix();
  79256. }
  79257. this._skeleton.computeAbsoluteTransforms();
  79258. var tmat = Bone._tmpMats[0];
  79259. tmat.copyFrom(this.getAbsoluteTransform());
  79260. if (mesh && wm) {
  79261. tmat.multiplyToRef(wm, tmat);
  79262. }
  79263. tmat.invert();
  79264. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79265. };
  79266. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79267. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79268. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79269. return Bone;
  79270. }(BABYLON.Node));
  79271. BABYLON.Bone = Bone;
  79272. })(BABYLON || (BABYLON = {}));
  79273. //# sourceMappingURL=babylon.bone.js.map
  79274. var BABYLON;
  79275. (function (BABYLON) {
  79276. /**
  79277. * Class used to apply inverse kinematics to bones
  79278. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79279. */
  79280. var BoneIKController = /** @class */ (function () {
  79281. /**
  79282. * Creates a new BoneIKController
  79283. * @param mesh defines the mesh to control
  79284. * @param bone defines the bone to control
  79285. * @param options defines options to set up the controller
  79286. */
  79287. function BoneIKController(mesh, bone, options) {
  79288. /**
  79289. * Gets or sets the target position
  79290. */
  79291. this.targetPosition = BABYLON.Vector3.Zero();
  79292. /**
  79293. * Gets or sets the pole target position
  79294. */
  79295. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79296. /**
  79297. * Gets or sets the pole target local offset
  79298. */
  79299. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79300. /**
  79301. * Gets or sets the pole angle
  79302. */
  79303. this.poleAngle = 0;
  79304. /**
  79305. * 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)
  79306. */
  79307. this.slerpAmount = 1;
  79308. this._bone1Quat = BABYLON.Quaternion.Identity();
  79309. this._bone1Mat = BABYLON.Matrix.Identity();
  79310. this._bone2Ang = Math.PI;
  79311. this._maxAngle = Math.PI;
  79312. this._rightHandedSystem = false;
  79313. this._bendAxis = BABYLON.Vector3.Right();
  79314. this._slerping = false;
  79315. this._adjustRoll = 0;
  79316. this._bone2 = bone;
  79317. this._bone1 = bone.getParent();
  79318. if (!this._bone1) {
  79319. return;
  79320. }
  79321. this.mesh = mesh;
  79322. var bonePos = bone.getPosition();
  79323. if (bone.getAbsoluteTransform().determinant() > 0) {
  79324. this._rightHandedSystem = true;
  79325. this._bendAxis.x = 0;
  79326. this._bendAxis.y = 0;
  79327. this._bendAxis.z = -1;
  79328. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79329. this._adjustRoll = Math.PI * .5;
  79330. this._bendAxis.z = 1;
  79331. }
  79332. }
  79333. if (this._bone1.length) {
  79334. var boneScale1 = this._bone1.getScale();
  79335. var boneScale2 = this._bone2.getScale();
  79336. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79337. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79338. }
  79339. else if (this._bone1.children[0]) {
  79340. mesh.computeWorldMatrix(true);
  79341. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79342. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79343. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79344. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79345. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79346. }
  79347. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79348. this.maxAngle = Math.PI;
  79349. if (options) {
  79350. if (options.targetMesh) {
  79351. this.targetMesh = options.targetMesh;
  79352. this.targetMesh.computeWorldMatrix(true);
  79353. }
  79354. if (options.poleTargetMesh) {
  79355. this.poleTargetMesh = options.poleTargetMesh;
  79356. this.poleTargetMesh.computeWorldMatrix(true);
  79357. }
  79358. else if (options.poleTargetBone) {
  79359. this.poleTargetBone = options.poleTargetBone;
  79360. }
  79361. else if (this._bone1.getParent()) {
  79362. this.poleTargetBone = this._bone1.getParent();
  79363. }
  79364. if (options.poleTargetLocalOffset) {
  79365. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79366. }
  79367. if (options.poleAngle) {
  79368. this.poleAngle = options.poleAngle;
  79369. }
  79370. if (options.bendAxis) {
  79371. this._bendAxis.copyFrom(options.bendAxis);
  79372. }
  79373. if (options.maxAngle) {
  79374. this.maxAngle = options.maxAngle;
  79375. }
  79376. if (options.slerpAmount) {
  79377. this.slerpAmount = options.slerpAmount;
  79378. }
  79379. }
  79380. }
  79381. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79382. /**
  79383. * Gets or sets maximum allowed angle
  79384. */
  79385. get: function () {
  79386. return this._maxAngle;
  79387. },
  79388. set: function (value) {
  79389. this._setMaxAngle(value);
  79390. },
  79391. enumerable: true,
  79392. configurable: true
  79393. });
  79394. BoneIKController.prototype._setMaxAngle = function (ang) {
  79395. if (ang < 0) {
  79396. ang = 0;
  79397. }
  79398. if (ang > Math.PI || ang == undefined) {
  79399. ang = Math.PI;
  79400. }
  79401. this._maxAngle = ang;
  79402. var a = this._bone1Length;
  79403. var b = this._bone2Length;
  79404. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79405. };
  79406. /**
  79407. * Force the controller to update the bones
  79408. */
  79409. BoneIKController.prototype.update = function () {
  79410. var bone1 = this._bone1;
  79411. if (!bone1) {
  79412. return;
  79413. }
  79414. var target = this.targetPosition;
  79415. var poleTarget = this.poleTargetPosition;
  79416. var mat1 = BoneIKController._tmpMats[0];
  79417. var mat2 = BoneIKController._tmpMats[1];
  79418. if (this.targetMesh) {
  79419. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79420. }
  79421. if (this.poleTargetBone) {
  79422. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79423. }
  79424. else if (this.poleTargetMesh) {
  79425. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79426. }
  79427. var bonePos = BoneIKController._tmpVecs[0];
  79428. var zaxis = BoneIKController._tmpVecs[1];
  79429. var xaxis = BoneIKController._tmpVecs[2];
  79430. var yaxis = BoneIKController._tmpVecs[3];
  79431. var upAxis = BoneIKController._tmpVecs[4];
  79432. var _tmpQuat = BoneIKController._tmpQuat;
  79433. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79434. poleTarget.subtractToRef(bonePos, upAxis);
  79435. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79436. upAxis.y = 1;
  79437. }
  79438. else {
  79439. upAxis.normalize();
  79440. }
  79441. target.subtractToRef(bonePos, yaxis);
  79442. yaxis.normalize();
  79443. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79444. zaxis.normalize();
  79445. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79446. xaxis.normalize();
  79447. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79448. var a = this._bone1Length;
  79449. var b = this._bone2Length;
  79450. var c = BABYLON.Vector3.Distance(bonePos, target);
  79451. if (this._maxReach > 0) {
  79452. c = Math.min(this._maxReach, c);
  79453. }
  79454. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79455. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79456. if (acosa > 1) {
  79457. acosa = 1;
  79458. }
  79459. if (acosb > 1) {
  79460. acosb = 1;
  79461. }
  79462. if (acosa < -1) {
  79463. acosa = -1;
  79464. }
  79465. if (acosb < -1) {
  79466. acosb = -1;
  79467. }
  79468. var angA = Math.acos(acosa);
  79469. var angB = Math.acos(acosb);
  79470. var angC = -angA - angB;
  79471. if (this._rightHandedSystem) {
  79472. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79473. mat2.multiplyToRef(mat1, mat1);
  79474. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79475. mat2.multiplyToRef(mat1, mat1);
  79476. }
  79477. else {
  79478. var _tmpVec = BoneIKController._tmpVecs[5];
  79479. _tmpVec.copyFrom(this._bendAxis);
  79480. _tmpVec.x *= -1;
  79481. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79482. mat2.multiplyToRef(mat1, mat1);
  79483. }
  79484. if (this.poleAngle) {
  79485. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79486. mat1.multiplyToRef(mat2, mat1);
  79487. }
  79488. if (this._bone1) {
  79489. if (this.slerpAmount < 1) {
  79490. if (!this._slerping) {
  79491. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79492. }
  79493. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79494. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79495. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79496. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79497. this._slerping = true;
  79498. }
  79499. else {
  79500. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79501. this._bone1Mat.copyFrom(mat1);
  79502. this._slerping = false;
  79503. }
  79504. }
  79505. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79506. this._bone2Ang = angC;
  79507. };
  79508. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79509. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79510. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79511. return BoneIKController;
  79512. }());
  79513. BABYLON.BoneIKController = BoneIKController;
  79514. })(BABYLON || (BABYLON = {}));
  79515. //# sourceMappingURL=babylon.boneIKController.js.map
  79516. var BABYLON;
  79517. (function (BABYLON) {
  79518. /**
  79519. * Class used to make a bone look toward a point in space
  79520. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79521. */
  79522. var BoneLookController = /** @class */ (function () {
  79523. /**
  79524. * Create a BoneLookController
  79525. * @param mesh the mesh that the bone belongs to
  79526. * @param bone the bone that will be looking to the target
  79527. * @param target the target Vector3 to look at
  79528. * @param settings optional settings:
  79529. * * maxYaw: the maximum angle the bone will yaw to
  79530. * * minYaw: the minimum angle the bone will yaw to
  79531. * * maxPitch: the maximum angle the bone will pitch to
  79532. * * minPitch: the minimum angle the bone will yaw to
  79533. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79534. * * upAxis: the up axis of the coordinate system
  79535. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79536. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79537. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79538. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79539. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79540. * * adjustRoll: used to make an adjustment to the roll of the bone
  79541. **/
  79542. function BoneLookController(mesh, bone, target, options) {
  79543. /**
  79544. * The up axis of the coordinate system that is used when the bone is rotated
  79545. */
  79546. this.upAxis = BABYLON.Vector3.Up();
  79547. /**
  79548. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79549. */
  79550. this.upAxisSpace = BABYLON.Space.LOCAL;
  79551. /**
  79552. * Used to make an adjustment to the yaw of the bone
  79553. */
  79554. this.adjustYaw = 0;
  79555. /**
  79556. * Used to make an adjustment to the pitch of the bone
  79557. */
  79558. this.adjustPitch = 0;
  79559. /**
  79560. * Used to make an adjustment to the roll of the bone
  79561. */
  79562. this.adjustRoll = 0;
  79563. /**
  79564. * 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)
  79565. */
  79566. this.slerpAmount = 1;
  79567. this._boneQuat = BABYLON.Quaternion.Identity();
  79568. this._slerping = false;
  79569. this._firstFrameSkipped = false;
  79570. this._fowardAxis = BABYLON.Vector3.Forward();
  79571. this.mesh = mesh;
  79572. this.bone = bone;
  79573. this.target = target;
  79574. if (options) {
  79575. if (options.adjustYaw) {
  79576. this.adjustYaw = options.adjustYaw;
  79577. }
  79578. if (options.adjustPitch) {
  79579. this.adjustPitch = options.adjustPitch;
  79580. }
  79581. if (options.adjustRoll) {
  79582. this.adjustRoll = options.adjustRoll;
  79583. }
  79584. if (options.maxYaw != null) {
  79585. this.maxYaw = options.maxYaw;
  79586. }
  79587. else {
  79588. this.maxYaw = Math.PI;
  79589. }
  79590. if (options.minYaw != null) {
  79591. this.minYaw = options.minYaw;
  79592. }
  79593. else {
  79594. this.minYaw = -Math.PI;
  79595. }
  79596. if (options.maxPitch != null) {
  79597. this.maxPitch = options.maxPitch;
  79598. }
  79599. else {
  79600. this.maxPitch = Math.PI;
  79601. }
  79602. if (options.minPitch != null) {
  79603. this.minPitch = options.minPitch;
  79604. }
  79605. else {
  79606. this.minPitch = -Math.PI;
  79607. }
  79608. if (options.slerpAmount != null) {
  79609. this.slerpAmount = options.slerpAmount;
  79610. }
  79611. if (options.upAxis != null) {
  79612. this.upAxis = options.upAxis;
  79613. }
  79614. if (options.upAxisSpace != null) {
  79615. this.upAxisSpace = options.upAxisSpace;
  79616. }
  79617. if (options.yawAxis != null || options.pitchAxis != null) {
  79618. var newYawAxis = BABYLON.Axis.Y;
  79619. var newPitchAxis = BABYLON.Axis.X;
  79620. if (options.yawAxis != null) {
  79621. newYawAxis = options.yawAxis.clone();
  79622. newYawAxis.normalize();
  79623. }
  79624. if (options.pitchAxis != null) {
  79625. newPitchAxis = options.pitchAxis.clone();
  79626. newPitchAxis.normalize();
  79627. }
  79628. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79629. this._transformYawPitch = BABYLON.Matrix.Identity();
  79630. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79631. this._transformYawPitchInv = this._transformYawPitch.clone();
  79632. this._transformYawPitch.invert();
  79633. }
  79634. }
  79635. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79636. this.upAxisSpace = BABYLON.Space.LOCAL;
  79637. }
  79638. }
  79639. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79640. /**
  79641. * Gets or sets the minimum yaw angle that the bone can look to
  79642. */
  79643. get: function () {
  79644. return this._minYaw;
  79645. },
  79646. set: function (value) {
  79647. this._minYaw = value;
  79648. this._minYawSin = Math.sin(value);
  79649. this._minYawCos = Math.cos(value);
  79650. if (this._maxYaw != null) {
  79651. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79652. this._yawRange = this._maxYaw - this._minYaw;
  79653. }
  79654. },
  79655. enumerable: true,
  79656. configurable: true
  79657. });
  79658. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79659. /**
  79660. * Gets or sets the maximum yaw angle that the bone can look to
  79661. */
  79662. get: function () {
  79663. return this._maxYaw;
  79664. },
  79665. set: function (value) {
  79666. this._maxYaw = value;
  79667. this._maxYawSin = Math.sin(value);
  79668. this._maxYawCos = Math.cos(value);
  79669. if (this._minYaw != null) {
  79670. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79671. this._yawRange = this._maxYaw - this._minYaw;
  79672. }
  79673. },
  79674. enumerable: true,
  79675. configurable: true
  79676. });
  79677. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79678. /**
  79679. * Gets or sets the minimum pitch angle that the bone can look to
  79680. */
  79681. get: function () {
  79682. return this._minPitch;
  79683. },
  79684. set: function (value) {
  79685. this._minPitch = value;
  79686. this._minPitchTan = Math.tan(value);
  79687. },
  79688. enumerable: true,
  79689. configurable: true
  79690. });
  79691. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79692. /**
  79693. * Gets or sets the maximum pitch angle that the bone can look to
  79694. */
  79695. get: function () {
  79696. return this._maxPitch;
  79697. },
  79698. set: function (value) {
  79699. this._maxPitch = value;
  79700. this._maxPitchTan = Math.tan(value);
  79701. },
  79702. enumerable: true,
  79703. configurable: true
  79704. });
  79705. /**
  79706. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79707. */
  79708. BoneLookController.prototype.update = function () {
  79709. //skip the first frame when slerping so that the mesh rotation is correct
  79710. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79711. this._firstFrameSkipped = true;
  79712. return;
  79713. }
  79714. var bone = this.bone;
  79715. var bonePos = BoneLookController._tmpVecs[0];
  79716. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79717. var target = this.target;
  79718. var _tmpMat1 = BoneLookController._tmpMats[0];
  79719. var _tmpMat2 = BoneLookController._tmpMats[1];
  79720. var mesh = this.mesh;
  79721. var parentBone = bone.getParent();
  79722. var upAxis = BoneLookController._tmpVecs[1];
  79723. upAxis.copyFrom(this.upAxis);
  79724. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79725. if (this._transformYawPitch) {
  79726. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79727. }
  79728. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79729. }
  79730. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79731. mesh.getDirectionToRef(upAxis, upAxis);
  79732. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79733. upAxis.normalize();
  79734. }
  79735. }
  79736. var checkYaw = false;
  79737. var checkPitch = false;
  79738. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79739. checkYaw = true;
  79740. }
  79741. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79742. checkPitch = true;
  79743. }
  79744. if (checkYaw || checkPitch) {
  79745. var spaceMat = BoneLookController._tmpMats[2];
  79746. var spaceMatInv = BoneLookController._tmpMats[3];
  79747. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79748. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79749. }
  79750. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79751. spaceMat.copyFrom(mesh.getWorldMatrix());
  79752. }
  79753. else {
  79754. var forwardAxis = BoneLookController._tmpVecs[2];
  79755. forwardAxis.copyFrom(this._fowardAxis);
  79756. if (this._transformYawPitch) {
  79757. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79758. }
  79759. if (parentBone) {
  79760. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79761. }
  79762. else {
  79763. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79764. }
  79765. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79766. rightAxis.normalize();
  79767. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79768. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79769. }
  79770. spaceMat.invertToRef(spaceMatInv);
  79771. var xzlen = null;
  79772. if (checkPitch) {
  79773. var localTarget = BoneLookController._tmpVecs[3];
  79774. target.subtractToRef(bonePos, localTarget);
  79775. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79776. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79777. var pitch = Math.atan2(localTarget.y, xzlen);
  79778. var newPitch = pitch;
  79779. if (pitch > this._maxPitch) {
  79780. localTarget.y = this._maxPitchTan * xzlen;
  79781. newPitch = this._maxPitch;
  79782. }
  79783. else if (pitch < this._minPitch) {
  79784. localTarget.y = this._minPitchTan * xzlen;
  79785. newPitch = this._minPitch;
  79786. }
  79787. if (pitch != newPitch) {
  79788. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79789. localTarget.addInPlace(bonePos);
  79790. target = localTarget;
  79791. }
  79792. }
  79793. if (checkYaw) {
  79794. var localTarget = BoneLookController._tmpVecs[4];
  79795. target.subtractToRef(bonePos, localTarget);
  79796. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79797. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79798. var newYaw = yaw;
  79799. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79800. if (xzlen == null) {
  79801. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79802. }
  79803. if (this._yawRange > Math.PI) {
  79804. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79805. localTarget.z = this._maxYawCos * xzlen;
  79806. localTarget.x = this._maxYawSin * xzlen;
  79807. newYaw = this._maxYaw;
  79808. }
  79809. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79810. localTarget.z = this._minYawCos * xzlen;
  79811. localTarget.x = this._minYawSin * xzlen;
  79812. newYaw = this._minYaw;
  79813. }
  79814. }
  79815. else {
  79816. if (yaw > this._maxYaw) {
  79817. localTarget.z = this._maxYawCos * xzlen;
  79818. localTarget.x = this._maxYawSin * xzlen;
  79819. newYaw = this._maxYaw;
  79820. }
  79821. else if (yaw < this._minYaw) {
  79822. localTarget.z = this._minYawCos * xzlen;
  79823. localTarget.x = this._minYawSin * xzlen;
  79824. newYaw = this._minYaw;
  79825. }
  79826. }
  79827. }
  79828. if (this._slerping && this._yawRange > Math.PI) {
  79829. //are we going to be crossing into the min/max region?
  79830. var boneFwd = BoneLookController._tmpVecs[8];
  79831. boneFwd.copyFrom(BABYLON.Axis.Z);
  79832. if (this._transformYawPitch) {
  79833. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79834. }
  79835. var boneRotMat = BoneLookController._tmpMats[4];
  79836. this._boneQuat.toRotationMatrix(boneRotMat);
  79837. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79838. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79839. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79840. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79841. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79842. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79843. if (angBtwTar > angBtwMidYaw) {
  79844. if (xzlen == null) {
  79845. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79846. }
  79847. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79848. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79849. if (angBtwMin < angBtwMax) {
  79850. newYaw = boneYaw + Math.PI * .75;
  79851. localTarget.z = Math.cos(newYaw) * xzlen;
  79852. localTarget.x = Math.sin(newYaw) * xzlen;
  79853. }
  79854. else {
  79855. newYaw = boneYaw - Math.PI * .75;
  79856. localTarget.z = Math.cos(newYaw) * xzlen;
  79857. localTarget.x = Math.sin(newYaw) * xzlen;
  79858. }
  79859. }
  79860. }
  79861. if (yaw != newYaw) {
  79862. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79863. localTarget.addInPlace(bonePos);
  79864. target = localTarget;
  79865. }
  79866. }
  79867. }
  79868. var zaxis = BoneLookController._tmpVecs[5];
  79869. var xaxis = BoneLookController._tmpVecs[6];
  79870. var yaxis = BoneLookController._tmpVecs[7];
  79871. var _tmpQuat = BoneLookController._tmpQuat;
  79872. target.subtractToRef(bonePos, zaxis);
  79873. zaxis.normalize();
  79874. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79875. xaxis.normalize();
  79876. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79877. yaxis.normalize();
  79878. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79879. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79880. return;
  79881. }
  79882. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79883. return;
  79884. }
  79885. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79886. return;
  79887. }
  79888. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79889. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79890. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79891. }
  79892. if (this.slerpAmount < 1) {
  79893. if (!this._slerping) {
  79894. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79895. }
  79896. if (this._transformYawPitch) {
  79897. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79898. }
  79899. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79900. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79901. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79902. this._slerping = true;
  79903. }
  79904. else {
  79905. if (this._transformYawPitch) {
  79906. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79907. }
  79908. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79909. this._slerping = false;
  79910. }
  79911. };
  79912. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79913. var angDiff = ang2 - ang1;
  79914. angDiff %= Math.PI * 2;
  79915. if (angDiff > Math.PI) {
  79916. angDiff -= Math.PI * 2;
  79917. }
  79918. else if (angDiff < -Math.PI) {
  79919. angDiff += Math.PI * 2;
  79920. }
  79921. return angDiff;
  79922. };
  79923. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79924. ang1 %= (2 * Math.PI);
  79925. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79926. ang2 %= (2 * Math.PI);
  79927. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79928. var ab = 0;
  79929. if (ang1 < ang2) {
  79930. ab = ang2 - ang1;
  79931. }
  79932. else {
  79933. ab = ang1 - ang2;
  79934. }
  79935. if (ab > Math.PI) {
  79936. ab = Math.PI * 2 - ab;
  79937. }
  79938. return ab;
  79939. };
  79940. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79941. ang %= (2 * Math.PI);
  79942. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79943. ang1 %= (2 * Math.PI);
  79944. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79945. ang2 %= (2 * Math.PI);
  79946. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79947. if (ang1 < ang2) {
  79948. if (ang > ang1 && ang < ang2) {
  79949. return true;
  79950. }
  79951. }
  79952. else {
  79953. if (ang > ang2 && ang < ang1) {
  79954. return true;
  79955. }
  79956. }
  79957. return false;
  79958. };
  79959. 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()];
  79960. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79961. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79962. return BoneLookController;
  79963. }());
  79964. BABYLON.BoneLookController = BoneLookController;
  79965. })(BABYLON || (BABYLON = {}));
  79966. //# sourceMappingURL=babylon.boneLookController.js.map
  79967. var BABYLON;
  79968. (function (BABYLON) {
  79969. /**
  79970. * Class used to handle skinning animations
  79971. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79972. */
  79973. var Skeleton = /** @class */ (function () {
  79974. /**
  79975. * Creates a new skeleton
  79976. * @param name defines the skeleton name
  79977. * @param id defines the skeleton Id
  79978. * @param scene defines the hosting scene
  79979. */
  79980. function Skeleton(
  79981. /** defines the skeleton name */
  79982. name,
  79983. /** defines the skeleton Id */
  79984. id, scene) {
  79985. this.name = name;
  79986. this.id = id;
  79987. /**
  79988. * Gets the list of child bones
  79989. */
  79990. this.bones = new Array();
  79991. /**
  79992. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79993. */
  79994. this.needInitialSkinMatrix = false;
  79995. this._isDirty = true;
  79996. this._meshesWithPoseMatrix = new Array();
  79997. this._identity = BABYLON.Matrix.Identity();
  79998. this._ranges = {};
  79999. this._lastAbsoluteTransformsUpdateId = -1;
  80000. /**
  80001. * Specifies if the skeleton should be serialized
  80002. */
  80003. this.doNotSerialize = false;
  80004. this._animationPropertiesOverride = null;
  80005. // Events
  80006. /**
  80007. * An observable triggered before computing the skeleton's matrices
  80008. */
  80009. this.onBeforeComputeObservable = new BABYLON.Observable();
  80010. this.bones = [];
  80011. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80012. scene.skeletons.push(this);
  80013. //make sure it will recalculate the matrix next time prepare is called.
  80014. this._isDirty = true;
  80015. }
  80016. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80017. /**
  80018. * Gets or sets the animation properties override
  80019. */
  80020. get: function () {
  80021. if (!this._animationPropertiesOverride) {
  80022. return this._scene.animationPropertiesOverride;
  80023. }
  80024. return this._animationPropertiesOverride;
  80025. },
  80026. set: function (value) {
  80027. this._animationPropertiesOverride = value;
  80028. },
  80029. enumerable: true,
  80030. configurable: true
  80031. });
  80032. // Members
  80033. /**
  80034. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80035. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80036. * @returns a Float32Array containing matrices data
  80037. */
  80038. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80039. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80040. return mesh._bonesTransformMatrices;
  80041. }
  80042. if (!this._transformMatrices) {
  80043. this.prepare();
  80044. }
  80045. return this._transformMatrices;
  80046. };
  80047. /**
  80048. * Gets the current hosting scene
  80049. * @returns a scene object
  80050. */
  80051. Skeleton.prototype.getScene = function () {
  80052. return this._scene;
  80053. };
  80054. // Methods
  80055. /**
  80056. * Gets a string representing the current skeleton data
  80057. * @param fullDetails defines a boolean indicating if we want a verbose version
  80058. * @returns a string representing the current skeleton data
  80059. */
  80060. Skeleton.prototype.toString = function (fullDetails) {
  80061. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80062. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80063. if (fullDetails) {
  80064. ret += ", Ranges: {";
  80065. var first = true;
  80066. for (var name_1 in this._ranges) {
  80067. if (first) {
  80068. ret += ", ";
  80069. first = false;
  80070. }
  80071. ret += name_1;
  80072. }
  80073. ret += "}";
  80074. }
  80075. return ret;
  80076. };
  80077. /**
  80078. * Get bone's index searching by name
  80079. * @param name defines bone's name to search for
  80080. * @return the indice of the bone. Returns -1 if not found
  80081. */
  80082. Skeleton.prototype.getBoneIndexByName = function (name) {
  80083. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80084. if (this.bones[boneIndex].name === name) {
  80085. return boneIndex;
  80086. }
  80087. }
  80088. return -1;
  80089. };
  80090. /**
  80091. * Creater a new animation range
  80092. * @param name defines the name of the range
  80093. * @param from defines the start key
  80094. * @param to defines the end key
  80095. */
  80096. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80097. // check name not already in use
  80098. if (!this._ranges[name]) {
  80099. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80100. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80101. if (this.bones[i].animations[0]) {
  80102. this.bones[i].animations[0].createRange(name, from, to);
  80103. }
  80104. }
  80105. }
  80106. };
  80107. /**
  80108. * Delete a specific animation range
  80109. * @param name defines the name of the range
  80110. * @param deleteFrames defines if frames must be removed as well
  80111. */
  80112. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80113. if (deleteFrames === void 0) { deleteFrames = true; }
  80114. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80115. if (this.bones[i].animations[0]) {
  80116. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80117. }
  80118. }
  80119. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80120. };
  80121. /**
  80122. * Gets a specific animation range
  80123. * @param name defines the name of the range to look for
  80124. * @returns the requested animation range or null if not found
  80125. */
  80126. Skeleton.prototype.getAnimationRange = function (name) {
  80127. return this._ranges[name];
  80128. };
  80129. /**
  80130. * Gets the list of all animation ranges defined on this skeleton
  80131. * @returns an array
  80132. */
  80133. Skeleton.prototype.getAnimationRanges = function () {
  80134. var animationRanges = [];
  80135. var name;
  80136. var i = 0;
  80137. for (name in this._ranges) {
  80138. animationRanges[i] = this._ranges[name];
  80139. i++;
  80140. }
  80141. return animationRanges;
  80142. };
  80143. /**
  80144. * Copy animation range from a source skeleton.
  80145. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80146. * @param source defines the source skeleton
  80147. * @param name defines the name of the range to copy
  80148. * @param rescaleAsRequired defines if rescaling must be applied if required
  80149. * @returns true if operation was successful
  80150. */
  80151. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80152. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80153. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80154. return false;
  80155. }
  80156. var ret = true;
  80157. var frameOffset = this._getHighestAnimationFrame() + 1;
  80158. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80159. var boneDict = {};
  80160. var sourceBones = source.bones;
  80161. var nBones;
  80162. var i;
  80163. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80164. boneDict[sourceBones[i].name] = sourceBones[i];
  80165. }
  80166. if (this.bones.length !== sourceBones.length) {
  80167. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80168. ret = false;
  80169. }
  80170. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80171. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80172. var boneName = this.bones[i].name;
  80173. var sourceBone = boneDict[boneName];
  80174. if (sourceBone) {
  80175. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80176. }
  80177. else {
  80178. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80179. ret = false;
  80180. }
  80181. }
  80182. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80183. var range = source.getAnimationRange(name);
  80184. if (range) {
  80185. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80186. }
  80187. return ret;
  80188. };
  80189. /**
  80190. * Forces the skeleton to go to rest pose
  80191. */
  80192. Skeleton.prototype.returnToRest = function () {
  80193. for (var index = 0; index < this.bones.length; index++) {
  80194. this.bones[index].returnToRest();
  80195. }
  80196. };
  80197. Skeleton.prototype._getHighestAnimationFrame = function () {
  80198. var ret = 0;
  80199. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80200. if (this.bones[i].animations[0]) {
  80201. var highest = this.bones[i].animations[0].getHighestFrame();
  80202. if (ret < highest) {
  80203. ret = highest;
  80204. }
  80205. }
  80206. }
  80207. return ret;
  80208. };
  80209. /**
  80210. * Begin a specific animation range
  80211. * @param name defines the name of the range to start
  80212. * @param loop defines if looping must be turned on (false by default)
  80213. * @param speedRatio defines the speed ratio to apply (1 by default)
  80214. * @param onAnimationEnd defines a callback which will be called when animation will end
  80215. * @returns a new animatable
  80216. */
  80217. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80218. var range = this.getAnimationRange(name);
  80219. if (!range) {
  80220. return null;
  80221. }
  80222. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80223. };
  80224. /** @hidden */
  80225. Skeleton.prototype._markAsDirty = function () {
  80226. this._isDirty = true;
  80227. };
  80228. /** @hidden */
  80229. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80230. this._meshesWithPoseMatrix.push(mesh);
  80231. };
  80232. /** @hidden */
  80233. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80234. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80235. if (index > -1) {
  80236. this._meshesWithPoseMatrix.splice(index, 1);
  80237. }
  80238. };
  80239. /** @hidden */
  80240. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80241. this.onBeforeComputeObservable.notifyObservers(this);
  80242. for (var index = 0; index < this.bones.length; index++) {
  80243. var bone = this.bones[index];
  80244. var parentBone = bone.getParent();
  80245. if (parentBone) {
  80246. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80247. }
  80248. else {
  80249. if (initialSkinMatrix) {
  80250. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80251. }
  80252. else {
  80253. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80254. }
  80255. }
  80256. if (bone._index !== -1) {
  80257. var mappedIndex = bone._index === null ? index : bone._index;
  80258. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80259. }
  80260. }
  80261. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80262. };
  80263. /**
  80264. * Build all resources required to render a skeleton
  80265. */
  80266. Skeleton.prototype.prepare = function () {
  80267. if (!this._isDirty) {
  80268. return;
  80269. }
  80270. if (this.needInitialSkinMatrix) {
  80271. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80272. var mesh = this._meshesWithPoseMatrix[index];
  80273. var poseMatrix = mesh.getPoseMatrix();
  80274. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80275. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80276. }
  80277. if (this._synchronizedWithMesh !== mesh) {
  80278. this._synchronizedWithMesh = mesh;
  80279. // Prepare bones
  80280. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80281. var bone = this.bones[boneIndex];
  80282. if (!bone.getParent()) {
  80283. var matrix = bone.getBaseMatrix();
  80284. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80285. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80286. }
  80287. }
  80288. }
  80289. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80290. }
  80291. }
  80292. else {
  80293. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80294. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80295. }
  80296. this._computeTransformMatrices(this._transformMatrices, null);
  80297. }
  80298. this._isDirty = false;
  80299. this._scene._activeBones.addCount(this.bones.length, false);
  80300. };
  80301. /**
  80302. * Gets the list of animatables currently running for this skeleton
  80303. * @returns an array of animatables
  80304. */
  80305. Skeleton.prototype.getAnimatables = function () {
  80306. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80307. this._animatables = [];
  80308. for (var index = 0; index < this.bones.length; index++) {
  80309. this._animatables.push(this.bones[index]);
  80310. }
  80311. }
  80312. return this._animatables;
  80313. };
  80314. /**
  80315. * Clone the current skeleton
  80316. * @param name defines the name of the new skeleton
  80317. * @param id defines the id of the enw skeleton
  80318. * @returns the new skeleton
  80319. */
  80320. Skeleton.prototype.clone = function (name, id) {
  80321. var result = new Skeleton(name, id || name, this._scene);
  80322. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80323. for (var index = 0; index < this.bones.length; index++) {
  80324. var source = this.bones[index];
  80325. var parentBone = null;
  80326. var parent_1 = source.getParent();
  80327. if (parent_1) {
  80328. var parentIndex = this.bones.indexOf(parent_1);
  80329. parentBone = result.bones[parentIndex];
  80330. }
  80331. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80332. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80333. }
  80334. if (this._ranges) {
  80335. result._ranges = {};
  80336. for (var rangeName in this._ranges) {
  80337. var range = this._ranges[rangeName];
  80338. if (range) {
  80339. result._ranges[rangeName] = range.clone();
  80340. }
  80341. }
  80342. }
  80343. this._isDirty = true;
  80344. return result;
  80345. };
  80346. /**
  80347. * Enable animation blending for this skeleton
  80348. * @param blendingSpeed defines the blending speed to apply
  80349. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80350. */
  80351. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80352. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80353. this.bones.forEach(function (bone) {
  80354. bone.animations.forEach(function (animation) {
  80355. animation.enableBlending = true;
  80356. animation.blendingSpeed = blendingSpeed;
  80357. });
  80358. });
  80359. };
  80360. /**
  80361. * Releases all resources associated with the current skeleton
  80362. */
  80363. Skeleton.prototype.dispose = function () {
  80364. this._meshesWithPoseMatrix = [];
  80365. // Animations
  80366. this.getScene().stopAnimation(this);
  80367. // Remove from scene
  80368. this.getScene().removeSkeleton(this);
  80369. };
  80370. /**
  80371. * Serialize the skeleton in a JSON object
  80372. * @returns a JSON object
  80373. */
  80374. Skeleton.prototype.serialize = function () {
  80375. var serializationObject = {};
  80376. serializationObject.name = this.name;
  80377. serializationObject.id = this.id;
  80378. if (this.dimensionsAtRest) {
  80379. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80380. }
  80381. serializationObject.bones = [];
  80382. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80383. for (var index = 0; index < this.bones.length; index++) {
  80384. var bone = this.bones[index];
  80385. var parent_2 = bone.getParent();
  80386. var serializedBone = {
  80387. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80388. name: bone.name,
  80389. matrix: bone.getBaseMatrix().toArray(),
  80390. rest: bone.getRestPose().toArray()
  80391. };
  80392. serializationObject.bones.push(serializedBone);
  80393. if (bone.length) {
  80394. serializedBone.length = bone.length;
  80395. }
  80396. if (bone.metadata) {
  80397. serializedBone.metadata = bone.metadata;
  80398. }
  80399. if (bone.animations && bone.animations.length > 0) {
  80400. serializedBone.animation = bone.animations[0].serialize();
  80401. }
  80402. serializationObject.ranges = [];
  80403. for (var name in this._ranges) {
  80404. var source = this._ranges[name];
  80405. if (!source) {
  80406. continue;
  80407. }
  80408. var range = {};
  80409. range.name = name;
  80410. range.from = source.from;
  80411. range.to = source.to;
  80412. serializationObject.ranges.push(range);
  80413. }
  80414. }
  80415. return serializationObject;
  80416. };
  80417. /**
  80418. * Creates a new skeleton from serialized data
  80419. * @param parsedSkeleton defines the serialized data
  80420. * @param scene defines the hosting scene
  80421. * @returns a new skeleton
  80422. */
  80423. Skeleton.Parse = function (parsedSkeleton, scene) {
  80424. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80425. if (parsedSkeleton.dimensionsAtRest) {
  80426. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80427. }
  80428. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80429. var index;
  80430. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80431. var parsedBone = parsedSkeleton.bones[index];
  80432. var parentBone = null;
  80433. if (parsedBone.parentBoneIndex > -1) {
  80434. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80435. }
  80436. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80437. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80438. if (parsedBone.length) {
  80439. bone.length = parsedBone.length;
  80440. }
  80441. if (parsedBone.metadata) {
  80442. bone.metadata = parsedBone.metadata;
  80443. }
  80444. if (parsedBone.animation) {
  80445. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80446. }
  80447. }
  80448. // placed after bones, so createAnimationRange can cascade down
  80449. if (parsedSkeleton.ranges) {
  80450. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80451. var data = parsedSkeleton.ranges[index];
  80452. skeleton.createAnimationRange(data.name, data.from, data.to);
  80453. }
  80454. }
  80455. return skeleton;
  80456. };
  80457. /**
  80458. * Compute all node absolute transforms
  80459. * @param forceUpdate defines if computation must be done even if cache is up to date
  80460. */
  80461. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80462. if (forceUpdate === void 0) { forceUpdate = false; }
  80463. var renderId = this._scene.getRenderId();
  80464. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80465. this.bones[0].computeAbsoluteTransforms();
  80466. this._lastAbsoluteTransformsUpdateId = renderId;
  80467. }
  80468. };
  80469. /**
  80470. * Gets the root pose matrix
  80471. * @returns a matrix
  80472. */
  80473. Skeleton.prototype.getPoseMatrix = function () {
  80474. var poseMatrix = null;
  80475. if (this._meshesWithPoseMatrix.length > 0) {
  80476. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80477. }
  80478. return poseMatrix;
  80479. };
  80480. /**
  80481. * Sorts bones per internal index
  80482. */
  80483. Skeleton.prototype.sortBones = function () {
  80484. var bones = new Array();
  80485. var visited = new Array(this.bones.length);
  80486. for (var index = 0; index < this.bones.length; index++) {
  80487. this._sortBones(index, bones, visited);
  80488. }
  80489. this.bones = bones;
  80490. };
  80491. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80492. if (visited[index]) {
  80493. return;
  80494. }
  80495. visited[index] = true;
  80496. var bone = this.bones[index];
  80497. if (bone._index === undefined) {
  80498. bone._index = index;
  80499. }
  80500. var parentBone = bone.getParent();
  80501. if (parentBone) {
  80502. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80503. }
  80504. bones.push(bone);
  80505. };
  80506. return Skeleton;
  80507. }());
  80508. BABYLON.Skeleton = Skeleton;
  80509. })(BABYLON || (BABYLON = {}));
  80510. //# sourceMappingURL=babylon.skeleton.js.map
  80511. var BABYLON;
  80512. (function (BABYLON) {
  80513. var SphericalPolynomial = /** @class */ (function () {
  80514. function SphericalPolynomial() {
  80515. this.x = BABYLON.Vector3.Zero();
  80516. this.y = BABYLON.Vector3.Zero();
  80517. this.z = BABYLON.Vector3.Zero();
  80518. this.xx = BABYLON.Vector3.Zero();
  80519. this.yy = BABYLON.Vector3.Zero();
  80520. this.zz = BABYLON.Vector3.Zero();
  80521. this.xy = BABYLON.Vector3.Zero();
  80522. this.yz = BABYLON.Vector3.Zero();
  80523. this.zx = BABYLON.Vector3.Zero();
  80524. }
  80525. SphericalPolynomial.prototype.addAmbient = function (color) {
  80526. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80527. this.xx = this.xx.add(colorVector);
  80528. this.yy = this.yy.add(colorVector);
  80529. this.zz = this.zz.add(colorVector);
  80530. };
  80531. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80532. var result = new SphericalPolynomial();
  80533. result.x = harmonics.L11.scale(1.02333);
  80534. result.y = harmonics.L1_1.scale(1.02333);
  80535. result.z = harmonics.L10.scale(1.02333);
  80536. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80537. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80538. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80539. result.yz = harmonics.L2_1.scale(0.858086);
  80540. result.zx = harmonics.L21.scale(0.858086);
  80541. result.xy = harmonics.L2_2.scale(0.858086);
  80542. result.scale(1.0 / Math.PI);
  80543. return result;
  80544. };
  80545. SphericalPolynomial.prototype.scale = function (scale) {
  80546. this.x = this.x.scale(scale);
  80547. this.y = this.y.scale(scale);
  80548. this.z = this.z.scale(scale);
  80549. this.xx = this.xx.scale(scale);
  80550. this.yy = this.yy.scale(scale);
  80551. this.zz = this.zz.scale(scale);
  80552. this.yz = this.yz.scale(scale);
  80553. this.zx = this.zx.scale(scale);
  80554. this.xy = this.xy.scale(scale);
  80555. };
  80556. return SphericalPolynomial;
  80557. }());
  80558. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80559. var SphericalHarmonics = /** @class */ (function () {
  80560. function SphericalHarmonics() {
  80561. this.L00 = BABYLON.Vector3.Zero();
  80562. this.L1_1 = BABYLON.Vector3.Zero();
  80563. this.L10 = BABYLON.Vector3.Zero();
  80564. this.L11 = BABYLON.Vector3.Zero();
  80565. this.L2_2 = BABYLON.Vector3.Zero();
  80566. this.L2_1 = BABYLON.Vector3.Zero();
  80567. this.L20 = BABYLON.Vector3.Zero();
  80568. this.L21 = BABYLON.Vector3.Zero();
  80569. this.L22 = BABYLON.Vector3.Zero();
  80570. }
  80571. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80572. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80573. var c = colorVector.scale(deltaSolidAngle);
  80574. this.L00 = this.L00.add(c.scale(0.282095));
  80575. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80576. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80577. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80578. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80579. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80580. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80581. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80582. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80583. };
  80584. SphericalHarmonics.prototype.scale = function (scale) {
  80585. this.L00 = this.L00.scale(scale);
  80586. this.L1_1 = this.L1_1.scale(scale);
  80587. this.L10 = this.L10.scale(scale);
  80588. this.L11 = this.L11.scale(scale);
  80589. this.L2_2 = this.L2_2.scale(scale);
  80590. this.L2_1 = this.L2_1.scale(scale);
  80591. this.L20 = this.L20.scale(scale);
  80592. this.L21 = this.L21.scale(scale);
  80593. this.L22 = this.L22.scale(scale);
  80594. };
  80595. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80596. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80597. //
  80598. // E_lm = A_l * L_lm
  80599. //
  80600. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80601. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80602. // the scaling factors are given in equation 9.
  80603. // Constant (Band 0)
  80604. this.L00 = this.L00.scale(3.141593);
  80605. // Linear (Band 1)
  80606. this.L1_1 = this.L1_1.scale(2.094395);
  80607. this.L10 = this.L10.scale(2.094395);
  80608. this.L11 = this.L11.scale(2.094395);
  80609. // Quadratic (Band 2)
  80610. this.L2_2 = this.L2_2.scale(0.785398);
  80611. this.L2_1 = this.L2_1.scale(0.785398);
  80612. this.L20 = this.L20.scale(0.785398);
  80613. this.L21 = this.L21.scale(0.785398);
  80614. this.L22 = this.L22.scale(0.785398);
  80615. };
  80616. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80617. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80618. // L = (1/pi) * E * rho
  80619. //
  80620. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80621. this.scale(1.0 / Math.PI);
  80622. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80623. // (The pixel shader must apply albedo after texture fetches, etc).
  80624. };
  80625. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80626. var result = new SphericalHarmonics();
  80627. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80628. result.L1_1 = polynomial.y.scale(0.977204);
  80629. result.L10 = polynomial.z.scale(0.977204);
  80630. result.L11 = polynomial.x.scale(0.977204);
  80631. result.L2_2 = polynomial.xy.scale(1.16538);
  80632. result.L2_1 = polynomial.yz.scale(1.16538);
  80633. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80634. result.L21 = polynomial.zx.scale(1.16538);
  80635. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80636. result.scale(Math.PI);
  80637. return result;
  80638. };
  80639. return SphericalHarmonics;
  80640. }());
  80641. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80642. })(BABYLON || (BABYLON = {}));
  80643. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80644. var BABYLON;
  80645. (function (BABYLON) {
  80646. var FileFaceOrientation = /** @class */ (function () {
  80647. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80648. this.name = name;
  80649. this.worldAxisForNormal = worldAxisForNormal;
  80650. this.worldAxisForFileX = worldAxisForFileX;
  80651. this.worldAxisForFileY = worldAxisForFileY;
  80652. }
  80653. return FileFaceOrientation;
  80654. }());
  80655. ;
  80656. /**
  80657. * Helper class dealing with the extraction of spherical polynomial dataArray
  80658. * from a cube map.
  80659. */
  80660. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80661. function CubeMapToSphericalPolynomialTools() {
  80662. }
  80663. /**
  80664. * Converts a texture to the according Spherical Polynomial data.
  80665. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80666. *
  80667. * @param texture The texture to extract the information from.
  80668. * @return The Spherical Polynomial data.
  80669. */
  80670. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80671. if (!texture.isCube) {
  80672. // Only supports cube Textures currently.
  80673. return null;
  80674. }
  80675. var size = texture.getSize().width;
  80676. var right = texture.readPixels(0);
  80677. var left = texture.readPixels(1);
  80678. var up;
  80679. var down;
  80680. if (texture.isRenderTarget) {
  80681. up = texture.readPixels(3);
  80682. down = texture.readPixels(2);
  80683. }
  80684. else {
  80685. up = texture.readPixels(2);
  80686. down = texture.readPixels(3);
  80687. }
  80688. var front = texture.readPixels(4);
  80689. var back = texture.readPixels(5);
  80690. var gammaSpace = texture.gammaSpace;
  80691. // Always read as RGBA.
  80692. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80693. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80694. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80695. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80696. }
  80697. var cubeInfo = {
  80698. size: size,
  80699. right: right,
  80700. left: left,
  80701. up: up,
  80702. down: down,
  80703. front: front,
  80704. back: back,
  80705. format: format,
  80706. type: type,
  80707. gammaSpace: gammaSpace,
  80708. };
  80709. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80710. };
  80711. /**
  80712. * Converts a cubemap to the according Spherical Polynomial data.
  80713. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80714. *
  80715. * @param cubeInfo The Cube map to extract the information from.
  80716. * @return The Spherical Polynomial data.
  80717. */
  80718. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80719. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80720. var totalSolidAngle = 0.0;
  80721. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80722. var du = 2.0 / cubeInfo.size;
  80723. var dv = du;
  80724. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80725. var minUV = du * 0.5 - 1.0;
  80726. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80727. var fileFace = this.FileFaces[faceIndex];
  80728. var dataArray = cubeInfo[fileFace.name];
  80729. var v = minUV;
  80730. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80731. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80732. // Because SP is still linear, so summation is fine in that basis.
  80733. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80734. for (var y = 0; y < cubeInfo.size; y++) {
  80735. var u = minUV;
  80736. for (var x = 0; x < cubeInfo.size; x++) {
  80737. // World direction (not normalised)
  80738. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80739. worldDirection.normalize();
  80740. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80741. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80742. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80743. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80744. // Handle Integer types.
  80745. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80746. r /= 255;
  80747. g /= 255;
  80748. b /= 255;
  80749. }
  80750. // Handle Gamma space textures.
  80751. if (cubeInfo.gammaSpace) {
  80752. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80753. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80754. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80755. }
  80756. var color = new BABYLON.Color3(r, g, b);
  80757. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80758. totalSolidAngle += deltaSolidAngle;
  80759. u += du;
  80760. }
  80761. v += dv;
  80762. }
  80763. }
  80764. // Solid angle for entire sphere is 4*pi
  80765. var sphereSolidAngle = 4.0 * Math.PI;
  80766. // Adjust the solid angle to allow for how many faces we processed.
  80767. var facesProcessed = 6.0;
  80768. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80769. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80770. // This is needed because the numerical integration over the cube uses a
  80771. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80772. // and also to compensate for accumulative error due to float precision in the summation.
  80773. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80774. sphericalHarmonics.scale(correctionFactor);
  80775. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80776. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80777. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80778. };
  80779. CubeMapToSphericalPolynomialTools.FileFaces = [
  80780. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80781. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80782. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80783. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80784. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80785. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80786. ];
  80787. return CubeMapToSphericalPolynomialTools;
  80788. }());
  80789. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80790. })(BABYLON || (BABYLON = {}));
  80791. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80792. var BABYLON;
  80793. (function (BABYLON) {
  80794. /**
  80795. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80796. */
  80797. var PanoramaToCubeMapTools = /** @class */ (function () {
  80798. function PanoramaToCubeMapTools() {
  80799. }
  80800. /**
  80801. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80802. *
  80803. * @param float32Array The source data.
  80804. * @param inputWidth The width of the input panorama.
  80805. * @param inputhHeight The height of the input panorama.
  80806. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80807. * @return The cubemap data
  80808. */
  80809. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80810. if (!float32Array) {
  80811. throw "ConvertPanoramaToCubemap: input cannot be null";
  80812. }
  80813. if (float32Array.length != inputWidth * inputHeight * 3) {
  80814. throw "ConvertPanoramaToCubemap: input size is wrong";
  80815. }
  80816. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80817. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80818. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80819. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80820. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80821. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80822. return {
  80823. front: textureFront,
  80824. back: textureBack,
  80825. left: textureLeft,
  80826. right: textureRight,
  80827. up: textureUp,
  80828. down: textureDown,
  80829. size: size,
  80830. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80831. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80832. gammaSpace: false,
  80833. };
  80834. };
  80835. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80836. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80837. var textureArray = new Float32Array(buffer);
  80838. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80839. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80840. var dy = 1 / texSize;
  80841. var fy = 0;
  80842. for (var y = 0; y < texSize; y++) {
  80843. var xv1 = faceData[0];
  80844. var xv2 = faceData[2];
  80845. for (var x = 0; x < texSize; x++) {
  80846. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80847. v.normalize();
  80848. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80849. // 3 channels per pixels
  80850. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80851. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80852. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80853. xv1 = xv1.add(rotDX1);
  80854. xv2 = xv2.add(rotDX2);
  80855. }
  80856. fy += dy;
  80857. }
  80858. return textureArray;
  80859. };
  80860. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80861. var theta = Math.atan2(vDir.z, vDir.x);
  80862. var phi = Math.acos(vDir.y);
  80863. while (theta < -Math.PI)
  80864. theta += 2 * Math.PI;
  80865. while (theta > Math.PI)
  80866. theta -= 2 * Math.PI;
  80867. var dx = theta / Math.PI;
  80868. var dy = phi / Math.PI;
  80869. // recenter.
  80870. dx = dx * 0.5 + 0.5;
  80871. var px = Math.round(dx * inputWidth);
  80872. if (px < 0)
  80873. px = 0;
  80874. else if (px >= inputWidth)
  80875. px = inputWidth - 1;
  80876. var py = Math.round(dy * inputHeight);
  80877. if (py < 0)
  80878. py = 0;
  80879. else if (py >= inputHeight)
  80880. py = inputHeight - 1;
  80881. var inputY = (inputHeight - py - 1);
  80882. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80883. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80884. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80885. return {
  80886. r: r,
  80887. g: g,
  80888. b: b
  80889. };
  80890. };
  80891. PanoramaToCubeMapTools.FACE_FRONT = [
  80892. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80893. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80894. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80895. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80896. ];
  80897. PanoramaToCubeMapTools.FACE_BACK = [
  80898. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80899. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80900. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80901. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80902. ];
  80903. PanoramaToCubeMapTools.FACE_RIGHT = [
  80904. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80905. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80906. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80907. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80908. ];
  80909. PanoramaToCubeMapTools.FACE_LEFT = [
  80910. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80911. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80912. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80913. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80914. ];
  80915. PanoramaToCubeMapTools.FACE_DOWN = [
  80916. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80917. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80918. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80919. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80920. ];
  80921. PanoramaToCubeMapTools.FACE_UP = [
  80922. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80923. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80924. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80925. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80926. ];
  80927. return PanoramaToCubeMapTools;
  80928. }());
  80929. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80930. })(BABYLON || (BABYLON = {}));
  80931. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80932. var BABYLON;
  80933. (function (BABYLON) {
  80934. ;
  80935. /**
  80936. * This groups tools to convert HDR texture to native colors array.
  80937. */
  80938. var HDRTools = /** @class */ (function () {
  80939. function HDRTools() {
  80940. }
  80941. HDRTools.Ldexp = function (mantissa, exponent) {
  80942. if (exponent > 1023) {
  80943. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80944. }
  80945. if (exponent < -1074) {
  80946. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80947. }
  80948. return mantissa * Math.pow(2, exponent);
  80949. };
  80950. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80951. if (exponent > 0) { /*nonzero pixel*/
  80952. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80953. float32array[index + 0] = red * exponent;
  80954. float32array[index + 1] = green * exponent;
  80955. float32array[index + 2] = blue * exponent;
  80956. }
  80957. else {
  80958. float32array[index + 0] = 0;
  80959. float32array[index + 1] = 0;
  80960. float32array[index + 2] = 0;
  80961. }
  80962. };
  80963. HDRTools.readStringLine = function (uint8array, startIndex) {
  80964. var line = "";
  80965. var character = "";
  80966. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80967. character = String.fromCharCode(uint8array[i]);
  80968. if (character == "\n") {
  80969. break;
  80970. }
  80971. line += character;
  80972. }
  80973. return line;
  80974. };
  80975. /**
  80976. * Reads header information from an RGBE texture stored in a native array.
  80977. * More information on this format are available here:
  80978. * https://en.wikipedia.org/wiki/RGBE_image_format
  80979. *
  80980. * @param uint8array The binary file stored in native array.
  80981. * @return The header information.
  80982. */
  80983. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80984. var height = 0;
  80985. var width = 0;
  80986. var line = this.readStringLine(uint8array, 0);
  80987. if (line[0] != '#' || line[1] != '?') {
  80988. throw "Bad HDR Format.";
  80989. }
  80990. var endOfHeader = false;
  80991. var findFormat = false;
  80992. var lineIndex = 0;
  80993. do {
  80994. lineIndex += (line.length + 1);
  80995. line = this.readStringLine(uint8array, lineIndex);
  80996. if (line == "FORMAT=32-bit_rle_rgbe") {
  80997. findFormat = true;
  80998. }
  80999. else if (line.length == 0) {
  81000. endOfHeader = true;
  81001. }
  81002. } while (!endOfHeader);
  81003. if (!findFormat) {
  81004. throw "HDR Bad header format, unsupported FORMAT";
  81005. }
  81006. lineIndex += (line.length + 1);
  81007. line = this.readStringLine(uint8array, lineIndex);
  81008. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81009. var match = sizeRegexp.exec(line);
  81010. // TODO. Support +Y and -X if needed.
  81011. if (!match || match.length < 3) {
  81012. throw "HDR Bad header format, no size";
  81013. }
  81014. width = parseInt(match[2]);
  81015. height = parseInt(match[1]);
  81016. if (width < 8 || width > 0x7fff) {
  81017. throw "HDR Bad header format, unsupported size";
  81018. }
  81019. lineIndex += (line.length + 1);
  81020. return {
  81021. height: height,
  81022. width: width,
  81023. dataPosition: lineIndex
  81024. };
  81025. };
  81026. /**
  81027. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81028. * This RGBE texture needs to store the information as a panorama.
  81029. *
  81030. * More information on this format are available here:
  81031. * https://en.wikipedia.org/wiki/RGBE_image_format
  81032. *
  81033. * @param buffer The binary file stored in an array buffer.
  81034. * @param size The expected size of the extracted cubemap.
  81035. * @return The Cube Map information.
  81036. */
  81037. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81038. var uint8array = new Uint8Array(buffer);
  81039. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81040. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81041. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81042. return cubeMapData;
  81043. };
  81044. /**
  81045. * Returns the pixels data extracted from an RGBE texture.
  81046. * This pixels will be stored left to right up to down in the R G B order in one array.
  81047. *
  81048. * More information on this format are available here:
  81049. * https://en.wikipedia.org/wiki/RGBE_image_format
  81050. *
  81051. * @param uint8array The binary file stored in an array buffer.
  81052. * @param hdrInfo The header information of the file.
  81053. * @return The pixels data in RGB right to left up to down order.
  81054. */
  81055. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81056. // Keep for multi format supports.
  81057. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81058. };
  81059. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81060. var num_scanlines = hdrInfo.height;
  81061. var scanline_width = hdrInfo.width;
  81062. var a, b, c, d, count;
  81063. var dataIndex = hdrInfo.dataPosition;
  81064. var index = 0, endIndex = 0, i = 0;
  81065. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81066. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81067. // 3 channels of 4 bytes per pixel in float.
  81068. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81069. var resultArray = new Float32Array(resultBuffer);
  81070. // read in each successive scanline
  81071. while (num_scanlines > 0) {
  81072. a = uint8array[dataIndex++];
  81073. b = uint8array[dataIndex++];
  81074. c = uint8array[dataIndex++];
  81075. d = uint8array[dataIndex++];
  81076. if (a != 2 || b != 2 || (c & 0x80)) {
  81077. // this file is not run length encoded
  81078. throw "HDR Bad header format, not RLE";
  81079. }
  81080. if (((c << 8) | d) != scanline_width) {
  81081. throw "HDR Bad header format, wrong scan line width";
  81082. }
  81083. index = 0;
  81084. // read each of the four channels for the scanline into the buffer
  81085. for (i = 0; i < 4; i++) {
  81086. endIndex = (i + 1) * scanline_width;
  81087. while (index < endIndex) {
  81088. a = uint8array[dataIndex++];
  81089. b = uint8array[dataIndex++];
  81090. if (a > 128) {
  81091. // a run of the same value
  81092. count = a - 128;
  81093. if ((count == 0) || (count > endIndex - index)) {
  81094. throw "HDR Bad Format, bad scanline data (run)";
  81095. }
  81096. while (count-- > 0) {
  81097. scanLineArray[index++] = b;
  81098. }
  81099. }
  81100. else {
  81101. // a non-run
  81102. count = a;
  81103. if ((count == 0) || (count > endIndex - index)) {
  81104. throw "HDR Bad Format, bad scanline data (non-run)";
  81105. }
  81106. scanLineArray[index++] = b;
  81107. if (--count > 0) {
  81108. for (var j = 0; j < count; j++) {
  81109. scanLineArray[index++] = uint8array[dataIndex++];
  81110. }
  81111. }
  81112. }
  81113. }
  81114. }
  81115. // now convert data from buffer into floats
  81116. for (i = 0; i < scanline_width; i++) {
  81117. a = scanLineArray[i];
  81118. b = scanLineArray[i + scanline_width];
  81119. c = scanLineArray[i + 2 * scanline_width];
  81120. d = scanLineArray[i + 3 * scanline_width];
  81121. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81122. }
  81123. num_scanlines--;
  81124. }
  81125. return resultArray;
  81126. };
  81127. return HDRTools;
  81128. }());
  81129. BABYLON.HDRTools = HDRTools;
  81130. })(BABYLON || (BABYLON = {}));
  81131. //# sourceMappingURL=babylon.hdr.js.map
  81132. var BABYLON;
  81133. (function (BABYLON) {
  81134. /**
  81135. * Sets of helpers addressing the serialization and deserialization of environment texture
  81136. * stored in a BabylonJS env file.
  81137. * Those files are usually stored as .env files.
  81138. */
  81139. var EnvironmentTextureTools = /** @class */ (function () {
  81140. function EnvironmentTextureTools() {
  81141. }
  81142. /**
  81143. * Gets the environment info from an env file.
  81144. * @param data The array buffer containing the .env bytes.
  81145. * @returns the environment file info (the json header) if successfully parsed.
  81146. */
  81147. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81148. var dataView = new DataView(data);
  81149. var pos = 0;
  81150. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81151. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81152. BABYLON.Tools.Error('Not a babylon environment map');
  81153. return null;
  81154. }
  81155. }
  81156. // Read json manifest - collect characters up to null terminator
  81157. var manifestString = '';
  81158. var charCode = 0x00;
  81159. while ((charCode = dataView.getUint8(pos++))) {
  81160. manifestString += String.fromCharCode(charCode);
  81161. }
  81162. var manifest = JSON.parse(manifestString);
  81163. if (manifest.specular) {
  81164. // Extend the header with the position of the payload.
  81165. manifest.specular.specularDataPosition = pos;
  81166. }
  81167. return manifest;
  81168. };
  81169. /**
  81170. * Creates an environment texture from a loaded cube texture.
  81171. * @param texture defines the cube texture to convert in env file
  81172. * @return a promise containing the environment data if succesfull.
  81173. */
  81174. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81175. var _this = this;
  81176. var internalTexture = texture.getInternalTexture();
  81177. if (!internalTexture) {
  81178. return Promise.reject("The cube texture is invalid.");
  81179. }
  81180. if (!texture._prefiltered) {
  81181. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81182. }
  81183. var engine = internalTexture.getEngine();
  81184. if (engine && engine.premultipliedAlpha) {
  81185. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81186. }
  81187. var canvas = engine.getRenderingCanvas();
  81188. if (!canvas) {
  81189. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81190. }
  81191. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81192. if (!engine.getCaps().textureFloatRender) {
  81193. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81194. if (!engine.getCaps().textureHalfFloatRender) {
  81195. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81196. }
  81197. }
  81198. var cubeWidth = internalTexture.width;
  81199. var hostingScene = new BABYLON.Scene(engine);
  81200. var specularTextures = {};
  81201. var promises = [];
  81202. // Read and collect all mipmaps data from the cube.
  81203. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81204. mipmapsCount = Math.round(mipmapsCount);
  81205. var _loop_1 = function (i) {
  81206. var faceWidth = Math.pow(2, mipmapsCount - i);
  81207. var _loop_2 = function (face) {
  81208. var data = texture.readPixels(face, i);
  81209. // Creates a temp texture with the face data.
  81210. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81211. // And rgbdEncode them.
  81212. var promise = new Promise(function (resolve, reject) {
  81213. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  81214. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81215. rgbdPostProcess.onApply = function (effect) {
  81216. effect._bindTexture("textureSampler", tempTexture);
  81217. };
  81218. // As the process needs to happen on the main canvas, keep track of the current size
  81219. var currentW = engine.getRenderWidth();
  81220. var currentH = engine.getRenderHeight();
  81221. // Set the desired size for the texture
  81222. engine.setSize(faceWidth, faceWidth);
  81223. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81224. // Reading datas from WebGL
  81225. canvas.toBlob(function (blob) {
  81226. var fileReader = new FileReader();
  81227. fileReader.onload = function (event) {
  81228. var arrayBuffer = event.target.result;
  81229. specularTextures[i * 6 + face] = arrayBuffer;
  81230. resolve();
  81231. };
  81232. fileReader.readAsArrayBuffer(blob);
  81233. });
  81234. // Reapply the previous canvas size
  81235. engine.setSize(currentW, currentH);
  81236. });
  81237. });
  81238. promises.push(promise);
  81239. };
  81240. // All faces of the cube.
  81241. for (var face = 0; face < 6; face++) {
  81242. _loop_2(face);
  81243. }
  81244. };
  81245. for (var i = 0; i <= mipmapsCount; i++) {
  81246. _loop_1(i);
  81247. }
  81248. // Once all the textures haves been collected as RGBD stored in PNGs
  81249. return Promise.all(promises).then(function () {
  81250. // We can delete the hosting scene keeping track of all the creation objects
  81251. hostingScene.dispose();
  81252. // Creates the json header for the env texture
  81253. var info = {
  81254. version: 1,
  81255. width: cubeWidth,
  81256. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81257. specular: {
  81258. mipmaps: []
  81259. }
  81260. };
  81261. // Sets the specular image data information
  81262. var position = 0;
  81263. for (var i = 0; i <= mipmapsCount; i++) {
  81264. for (var face = 0; face < 6; face++) {
  81265. var byteLength = specularTextures[i * 6 + face].byteLength;
  81266. info.specular.mipmaps.push({
  81267. length: byteLength,
  81268. position: position
  81269. });
  81270. position += byteLength;
  81271. }
  81272. }
  81273. // Encode the JSON as an array buffer
  81274. var infoString = JSON.stringify(info);
  81275. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81276. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81277. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81278. infoView[i] = infoString.charCodeAt(i);
  81279. }
  81280. // Ends up with a null terminator for easier parsing
  81281. infoView[infoString.length] = 0x00;
  81282. // Computes the final required size and creates the storage
  81283. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81284. var finalBuffer = new ArrayBuffer(totalSize);
  81285. var finalBufferView = new Uint8Array(finalBuffer);
  81286. var dataView = new DataView(finalBuffer);
  81287. // Copy the magic bytes identifying the file in
  81288. var pos = 0;
  81289. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81290. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81291. }
  81292. // Add the json info
  81293. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81294. pos += infoBuffer.byteLength;
  81295. // Finally inserts the texture data
  81296. for (var i = 0; i <= mipmapsCount; i++) {
  81297. for (var face = 0; face < 6; face++) {
  81298. var dataBuffer = specularTextures[i * 6 + face];
  81299. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81300. pos += dataBuffer.byteLength;
  81301. }
  81302. }
  81303. // Voila
  81304. return finalBuffer;
  81305. });
  81306. };
  81307. /**
  81308. * Creates a JSON representation of the spherical data.
  81309. * @param texture defines the texture containing the polynomials
  81310. * @return the JSON representation of the spherical info
  81311. */
  81312. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81313. var polynmials = texture.sphericalPolynomial;
  81314. if (polynmials == null) {
  81315. return null;
  81316. }
  81317. return {
  81318. polynomials: true,
  81319. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81320. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81321. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81322. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81323. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81324. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81325. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81326. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81327. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81328. };
  81329. };
  81330. /**
  81331. * Uploads the texture info contained in the env file to te GPU.
  81332. * @param texture defines the internal texture to upload to
  81333. * @param arrayBuffer defines the buffer cotaining the data to load
  81334. * @param info defines the texture info retrieved through the GetEnvInfo method
  81335. * @returns a promise
  81336. */
  81337. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81338. if (info.version !== 1) {
  81339. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81340. }
  81341. var specularInfo = info.specular;
  81342. if (!specularInfo) {
  81343. // Nothing else parsed so far
  81344. return Promise.resolve();
  81345. }
  81346. // Double checks the enclosed info
  81347. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81348. mipmapsCount = Math.round(mipmapsCount) + 1;
  81349. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81350. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81351. }
  81352. // Gets everything ready.
  81353. var engine = texture.getEngine();
  81354. var expandTexture = false;
  81355. var generateNonLODTextures = false;
  81356. var rgbdPostProcess = null;
  81357. var cubeRtt = null;
  81358. var lodTextures = null;
  81359. var caps = engine.getCaps();
  81360. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81361. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81362. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81363. // Add extra process if texture lod is not supported
  81364. if (!caps.textureLOD) {
  81365. expandTexture = false;
  81366. generateNonLODTextures = true;
  81367. lodTextures = {};
  81368. }
  81369. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81370. else if (engine.webGLVersion < 2) {
  81371. expandTexture = false;
  81372. }
  81373. // If half float available we can uncompress the texture
  81374. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81375. expandTexture = true;
  81376. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81377. }
  81378. // If full float available we can uncompress the texture
  81379. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81380. expandTexture = true;
  81381. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81382. }
  81383. // Expand the texture if possible
  81384. if (expandTexture) {
  81385. // Simply run through the decode PP
  81386. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81387. texture._isRGBD = false;
  81388. texture.invertY = false;
  81389. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81390. generateDepthBuffer: false,
  81391. generateMipMaps: true,
  81392. generateStencilBuffer: false,
  81393. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81394. type: texture.type,
  81395. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81396. });
  81397. }
  81398. else {
  81399. texture._isRGBD = true;
  81400. texture.invertY = true;
  81401. // In case of missing support, applies the same patch than DDS files.
  81402. if (generateNonLODTextures) {
  81403. var mipSlices = 3;
  81404. var scale = texture._lodGenerationScale;
  81405. var offset = texture._lodGenerationOffset;
  81406. for (var i = 0; i < mipSlices; i++) {
  81407. //compute LOD from even spacing in smoothness (matching shader calculation)
  81408. var smoothness = i / (mipSlices - 1);
  81409. var roughness = 1 - smoothness;
  81410. var minLODIndex = offset; // roughness = 0
  81411. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81412. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81413. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81414. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81415. glTextureFromLod.isCube = true;
  81416. glTextureFromLod.invertY = true;
  81417. glTextureFromLod.generateMipMaps = false;
  81418. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81419. // Wrap in a base texture for easy binding.
  81420. var lodTexture = new BABYLON.BaseTexture(null);
  81421. lodTexture.isCube = true;
  81422. lodTexture._texture = glTextureFromLod;
  81423. lodTextures[mipmapIndex] = lodTexture;
  81424. switch (i) {
  81425. case 0:
  81426. texture._lodTextureLow = lodTexture;
  81427. break;
  81428. case 1:
  81429. texture._lodTextureMid = lodTexture;
  81430. break;
  81431. case 2:
  81432. texture._lodTextureHigh = lodTexture;
  81433. break;
  81434. }
  81435. }
  81436. }
  81437. }
  81438. var promises = [];
  81439. var _loop_3 = function (i) {
  81440. var _loop_4 = function (face) {
  81441. // Retrieves the face data
  81442. var imageData = specularInfo.mipmaps[i * 6 + face];
  81443. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81444. // Constructs an image element from bytes
  81445. var blob = new Blob([bytes], { type: 'image/png' });
  81446. var url = URL.createObjectURL(blob);
  81447. var image = new Image();
  81448. image.src = url;
  81449. // Enqueue promise to upload to the texture.
  81450. var promise = new Promise(function (resolve, reject) {
  81451. ;
  81452. image.onload = function () {
  81453. if (expandTexture) {
  81454. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81455. reject(message);
  81456. }, image);
  81457. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81458. // Uncompress the data to a RTT
  81459. rgbdPostProcess.onApply = function (effect) {
  81460. effect._bindTexture("textureSampler", tempTexture_1);
  81461. effect.setFloat2("scale", 1, 1);
  81462. };
  81463. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81464. // Cleanup
  81465. engine.restoreDefaultFramebuffer();
  81466. tempTexture_1.dispose();
  81467. window.URL.revokeObjectURL(url);
  81468. resolve();
  81469. });
  81470. }
  81471. else {
  81472. engine._uploadImageToTexture(texture, face, i, image);
  81473. // Upload the face to the none lod texture support
  81474. if (generateNonLODTextures) {
  81475. var lodTexture = lodTextures[i];
  81476. if (lodTexture) {
  81477. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  81478. }
  81479. }
  81480. resolve();
  81481. }
  81482. };
  81483. image.onerror = function (error) {
  81484. reject(error);
  81485. };
  81486. });
  81487. promises.push(promise);
  81488. };
  81489. // All faces
  81490. for (var face = 0; face < 6; face++) {
  81491. _loop_4(face);
  81492. }
  81493. };
  81494. // All mipmaps
  81495. for (var i = 0; i < mipmapsCount; i++) {
  81496. _loop_3(i);
  81497. }
  81498. // Once all done, finishes the cleanup and return
  81499. return Promise.all(promises).then(function () {
  81500. // Relase temp RTT.
  81501. if (cubeRtt) {
  81502. engine._releaseFramebufferObjects(cubeRtt);
  81503. cubeRtt._swapAndDie(texture);
  81504. }
  81505. // Relase temp Post Process.
  81506. if (rgbdPostProcess) {
  81507. rgbdPostProcess.dispose();
  81508. }
  81509. // Flag internal texture as ready in case they are in use.
  81510. if (generateNonLODTextures) {
  81511. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  81512. texture._lodTextureHigh._texture.isReady = true;
  81513. }
  81514. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  81515. texture._lodTextureMid._texture.isReady = true;
  81516. }
  81517. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  81518. texture._lodTextureLow._texture.isReady = true;
  81519. }
  81520. }
  81521. });
  81522. };
  81523. /**
  81524. * Uploads spherical polynomials information to the texture.
  81525. * @param texture defines the texture we are trying to upload the information to
  81526. * @param arrayBuffer defines the array buffer holding the data
  81527. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  81528. */
  81529. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  81530. if (info.version !== 1) {
  81531. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81532. }
  81533. var irradianceInfo = info.irradiance;
  81534. if (!irradianceInfo) {
  81535. return;
  81536. }
  81537. //harmonics now represent radiance
  81538. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  81539. if (irradianceInfo.polynomials) {
  81540. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  81541. }
  81542. else {
  81543. // convert From SH to SP.
  81544. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  81545. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  81546. }
  81547. };
  81548. /**
  81549. * Upload spherical polynomial coefficients to the texture
  81550. * @param polynmials Spherical polynmial coefficients (9)
  81551. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81552. */
  81553. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  81554. outPolynomialCoefficents.x.x = polynmials.x[0];
  81555. outPolynomialCoefficents.x.y = polynmials.x[1];
  81556. outPolynomialCoefficents.x.z = polynmials.x[2];
  81557. outPolynomialCoefficents.y.x = polynmials.y[0];
  81558. outPolynomialCoefficents.y.y = polynmials.y[1];
  81559. outPolynomialCoefficents.y.z = polynmials.y[2];
  81560. outPolynomialCoefficents.z.x = polynmials.z[0];
  81561. outPolynomialCoefficents.z.y = polynmials.z[1];
  81562. outPolynomialCoefficents.z.z = polynmials.z[2];
  81563. //xx
  81564. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  81565. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  81566. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  81567. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  81568. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  81569. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  81570. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  81571. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  81572. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  81573. //yz
  81574. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  81575. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  81576. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  81577. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  81578. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  81579. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  81580. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  81581. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  81582. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  81583. };
  81584. /**
  81585. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81586. * L = (1/pi) * E * rho
  81587. *
  81588. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81589. * @param harmonics Spherical harmonic coefficients (9)
  81590. */
  81591. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  81592. var scaleFactor = 1 / Math.PI;
  81593. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81594. // (The pixel shader must apply albedo after texture fetches, etc).
  81595. harmonics.l00[0] *= scaleFactor;
  81596. harmonics.l00[1] *= scaleFactor;
  81597. harmonics.l00[2] *= scaleFactor;
  81598. harmonics.l1_1[0] *= scaleFactor;
  81599. harmonics.l1_1[1] *= scaleFactor;
  81600. harmonics.l1_1[2] *= scaleFactor;
  81601. harmonics.l10[0] *= scaleFactor;
  81602. harmonics.l10[1] *= scaleFactor;
  81603. harmonics.l10[2] *= scaleFactor;
  81604. harmonics.l11[0] *= scaleFactor;
  81605. harmonics.l11[1] *= scaleFactor;
  81606. harmonics.l11[2] *= scaleFactor;
  81607. harmonics.l2_2[0] *= scaleFactor;
  81608. harmonics.l2_2[1] *= scaleFactor;
  81609. harmonics.l2_2[2] *= scaleFactor;
  81610. harmonics.l2_1[0] *= scaleFactor;
  81611. harmonics.l2_1[1] *= scaleFactor;
  81612. harmonics.l2_1[2] *= scaleFactor;
  81613. harmonics.l20[0] *= scaleFactor;
  81614. harmonics.l20[1] *= scaleFactor;
  81615. harmonics.l20[2] *= scaleFactor;
  81616. harmonics.l21[0] *= scaleFactor;
  81617. harmonics.l21[1] *= scaleFactor;
  81618. harmonics.l21[2] *= scaleFactor;
  81619. harmonics.l22[0] *= scaleFactor;
  81620. harmonics.l22[1] *= scaleFactor;
  81621. harmonics.l22[2] *= scaleFactor;
  81622. };
  81623. /**
  81624. * Convert spherical harmonics to spherical polynomial coefficients
  81625. * @param harmonics Spherical harmonic coefficients (9)
  81626. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81627. */
  81628. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  81629. var rPi = 1 / Math.PI;
  81630. //x
  81631. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  81632. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  81633. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  81634. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  81635. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  81636. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  81637. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  81638. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  81639. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  81640. //xx
  81641. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  81642. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  81643. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  81644. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  81645. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  81646. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  81647. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  81648. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  81649. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  81650. //yz
  81651. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  81652. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  81653. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  81654. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  81655. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  81656. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  81657. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  81658. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  81659. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  81660. };
  81661. /**
  81662. * Magic number identifying the env file.
  81663. */
  81664. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  81665. return EnvironmentTextureTools;
  81666. }());
  81667. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  81668. })(BABYLON || (BABYLON = {}));
  81669. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  81670. var BABYLON;
  81671. (function (BABYLON) {
  81672. /**
  81673. * This represents a texture coming from an HDR input.
  81674. *
  81675. * The only supported format is currently panorama picture stored in RGBE format.
  81676. * Example of such files can be found on HDRLib: http://hdrlib.com/
  81677. */
  81678. var HDRCubeTexture = /** @class */ (function (_super) {
  81679. __extends(HDRCubeTexture, _super);
  81680. /**
  81681. * Instantiates an HDRTexture from the following parameters.
  81682. *
  81683. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  81684. * @param scene The scene the texture will be used in
  81685. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  81686. * @param noMipmap Forces to not generate the mipmap if true
  81687. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  81688. * @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)
  81689. * @param reserved Reserved flag for internal use.
  81690. */
  81691. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  81692. if (noMipmap === void 0) { noMipmap = false; }
  81693. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81694. if (gammaSpace === void 0) { gammaSpace = false; }
  81695. if (reserved === void 0) { reserved = false; }
  81696. if (onLoad === void 0) { onLoad = null; }
  81697. if (onError === void 0) { onError = null; }
  81698. var _this = _super.call(this, scene) || this;
  81699. _this._generateHarmonics = true;
  81700. _this._onLoad = null;
  81701. _this._onError = null;
  81702. /**
  81703. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  81704. */
  81705. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  81706. _this._isBlocking = true;
  81707. _this._rotationY = 0;
  81708. /**
  81709. * Gets or sets the center of the bounding box associated with the cube texture
  81710. * It must define where the camera used to render the texture was set
  81711. */
  81712. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  81713. if (!url) {
  81714. return _this;
  81715. }
  81716. _this.name = url;
  81717. _this.url = url;
  81718. _this.hasAlpha = false;
  81719. _this.isCube = true;
  81720. _this._textureMatrix = BABYLON.Matrix.Identity();
  81721. _this._onLoad = onLoad;
  81722. _this._onError = onError;
  81723. _this.gammaSpace = gammaSpace;
  81724. _this._noMipmap = noMipmap;
  81725. _this._size = size;
  81726. _this._texture = _this._getFromCache(url, _this._noMipmap);
  81727. if (!_this._texture) {
  81728. if (!scene.useDelayedTextureLoading) {
  81729. _this.loadTexture();
  81730. }
  81731. else {
  81732. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81733. }
  81734. }
  81735. return _this;
  81736. }
  81737. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  81738. /**
  81739. * Gets wether or not the texture is blocking during loading.
  81740. */
  81741. get: function () {
  81742. return this._isBlocking;
  81743. },
  81744. /**
  81745. * Sets wether or not the texture is blocking during loading.
  81746. */
  81747. set: function (value) {
  81748. this._isBlocking = value;
  81749. },
  81750. enumerable: true,
  81751. configurable: true
  81752. });
  81753. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  81754. /**
  81755. * Gets texture matrix rotation angle around Y axis radians.
  81756. */
  81757. get: function () {
  81758. return this._rotationY;
  81759. },
  81760. /**
  81761. * Sets texture matrix rotation angle around Y axis in radians.
  81762. */
  81763. set: function (value) {
  81764. this._rotationY = value;
  81765. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  81766. },
  81767. enumerable: true,
  81768. configurable: true
  81769. });
  81770. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  81771. get: function () {
  81772. return this._boundingBoxSize;
  81773. },
  81774. /**
  81775. * Gets or sets the size of the bounding box associated with the cube texture
  81776. * When defined, the cubemap will switch to local mode
  81777. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  81778. * @example https://www.babylonjs-playground.com/#RNASML
  81779. */
  81780. set: function (value) {
  81781. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  81782. return;
  81783. }
  81784. this._boundingBoxSize = value;
  81785. var scene = this.getScene();
  81786. if (scene) {
  81787. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  81788. }
  81789. },
  81790. enumerable: true,
  81791. configurable: true
  81792. });
  81793. /**
  81794. * Occurs when the file is raw .hdr file.
  81795. */
  81796. HDRCubeTexture.prototype.loadTexture = function () {
  81797. var _this = this;
  81798. var callback = function (buffer) {
  81799. _this.lodGenerationOffset = 0.0;
  81800. _this.lodGenerationScale = 0.8;
  81801. var scene = _this.getScene();
  81802. if (!scene) {
  81803. return null;
  81804. }
  81805. // Extract the raw linear data.
  81806. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81807. // Generate harmonics if needed.
  81808. if (_this._generateHarmonics) {
  81809. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81810. _this.sphericalPolynomial = sphericalPolynomial;
  81811. }
  81812. var results = [];
  81813. var byteArray = null;
  81814. // Push each faces.
  81815. for (var j = 0; j < 6; j++) {
  81816. // Create uintarray fallback.
  81817. if (!scene.getEngine().getCaps().textureFloat) {
  81818. // 3 channels of 1 bytes per pixel in bytes.
  81819. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81820. byteArray = new Uint8Array(byteBuffer);
  81821. }
  81822. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81823. // If special cases.
  81824. if (_this.gammaSpace || byteArray) {
  81825. for (var i = 0; i < _this._size * _this._size; i++) {
  81826. // Put in gamma space if requested.
  81827. if (_this.gammaSpace) {
  81828. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81829. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81830. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81831. }
  81832. // Convert to int texture for fallback.
  81833. if (byteArray) {
  81834. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81835. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81836. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81837. // May use luminance instead if the result is not accurate.
  81838. var max = Math.max(Math.max(r, g), b);
  81839. if (max > 255) {
  81840. var scale = 255 / max;
  81841. r *= scale;
  81842. g *= scale;
  81843. b *= scale;
  81844. }
  81845. byteArray[(i * 3) + 0] = r;
  81846. byteArray[(i * 3) + 1] = g;
  81847. byteArray[(i * 3) + 2] = b;
  81848. }
  81849. }
  81850. }
  81851. if (byteArray) {
  81852. results.push(byteArray);
  81853. }
  81854. else {
  81855. results.push(dataFace);
  81856. }
  81857. }
  81858. return results;
  81859. };
  81860. var scene = this.getScene();
  81861. if (scene) {
  81862. 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);
  81863. }
  81864. };
  81865. HDRCubeTexture.prototype.clone = function () {
  81866. var scene = this.getScene();
  81867. if (!scene) {
  81868. return this;
  81869. }
  81870. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81871. // Base texture
  81872. newTexture.level = this.level;
  81873. newTexture.wrapU = this.wrapU;
  81874. newTexture.wrapV = this.wrapV;
  81875. newTexture.coordinatesIndex = this.coordinatesIndex;
  81876. newTexture.coordinatesMode = this.coordinatesMode;
  81877. return newTexture;
  81878. };
  81879. // Methods
  81880. HDRCubeTexture.prototype.delayLoad = function () {
  81881. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81882. return;
  81883. }
  81884. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81885. this._texture = this._getFromCache(this.url, this._noMipmap);
  81886. if (!this._texture) {
  81887. this.loadTexture();
  81888. }
  81889. };
  81890. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81891. return this._textureMatrix;
  81892. };
  81893. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81894. this._textureMatrix = value;
  81895. };
  81896. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81897. var texture = null;
  81898. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81899. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81900. texture.name = parsedTexture.name;
  81901. texture.hasAlpha = parsedTexture.hasAlpha;
  81902. texture.level = parsedTexture.level;
  81903. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81904. texture.isBlocking = parsedTexture.isBlocking;
  81905. }
  81906. if (texture) {
  81907. if (parsedTexture.boundingBoxPosition) {
  81908. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81909. }
  81910. if (parsedTexture.boundingBoxSize) {
  81911. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81912. }
  81913. if (parsedTexture.rotationY) {
  81914. texture.rotationY = parsedTexture.rotationY;
  81915. }
  81916. }
  81917. return texture;
  81918. };
  81919. HDRCubeTexture.prototype.serialize = function () {
  81920. if (!this.name) {
  81921. return null;
  81922. }
  81923. var serializationObject = {};
  81924. serializationObject.name = this.name;
  81925. serializationObject.hasAlpha = this.hasAlpha;
  81926. serializationObject.isCube = true;
  81927. serializationObject.level = this.level;
  81928. serializationObject.size = this._size;
  81929. serializationObject.coordinatesMode = this.coordinatesMode;
  81930. serializationObject.useInGammaSpace = this.gammaSpace;
  81931. serializationObject.generateHarmonics = this._generateHarmonics;
  81932. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81933. serializationObject.noMipmap = this._noMipmap;
  81934. serializationObject.isBlocking = this._isBlocking;
  81935. serializationObject.rotationY = this._rotationY;
  81936. return serializationObject;
  81937. };
  81938. HDRCubeTexture._facesMapping = [
  81939. "right",
  81940. "left",
  81941. "up",
  81942. "down",
  81943. "front",
  81944. "back"
  81945. ];
  81946. return HDRCubeTexture;
  81947. }(BABYLON.BaseTexture));
  81948. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81949. })(BABYLON || (BABYLON = {}));
  81950. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81951. var BABYLON;
  81952. (function (BABYLON) {
  81953. var IndexedVector2 = /** @class */ (function (_super) {
  81954. __extends(IndexedVector2, _super);
  81955. function IndexedVector2(original, index) {
  81956. var _this = _super.call(this, original.x, original.y) || this;
  81957. _this.index = index;
  81958. return _this;
  81959. }
  81960. return IndexedVector2;
  81961. }(BABYLON.Vector2));
  81962. var PolygonPoints = /** @class */ (function () {
  81963. function PolygonPoints() {
  81964. this.elements = new Array();
  81965. }
  81966. PolygonPoints.prototype.add = function (originalPoints) {
  81967. var _this = this;
  81968. var result = new Array();
  81969. originalPoints.forEach(function (point) {
  81970. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81971. var newPoint = new IndexedVector2(point, _this.elements.length);
  81972. result.push(newPoint);
  81973. _this.elements.push(newPoint);
  81974. }
  81975. });
  81976. return result;
  81977. };
  81978. PolygonPoints.prototype.computeBounds = function () {
  81979. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81980. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81981. this.elements.forEach(function (point) {
  81982. // x
  81983. if (point.x < lmin.x) {
  81984. lmin.x = point.x;
  81985. }
  81986. else if (point.x > lmax.x) {
  81987. lmax.x = point.x;
  81988. }
  81989. // y
  81990. if (point.y < lmin.y) {
  81991. lmin.y = point.y;
  81992. }
  81993. else if (point.y > lmax.y) {
  81994. lmax.y = point.y;
  81995. }
  81996. });
  81997. return {
  81998. min: lmin,
  81999. max: lmax,
  82000. width: lmax.x - lmin.x,
  82001. height: lmax.y - lmin.y
  82002. };
  82003. };
  82004. return PolygonPoints;
  82005. }());
  82006. var Polygon = /** @class */ (function () {
  82007. function Polygon() {
  82008. }
  82009. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82010. return [
  82011. new BABYLON.Vector2(xmin, ymin),
  82012. new BABYLON.Vector2(xmax, ymin),
  82013. new BABYLON.Vector2(xmax, ymax),
  82014. new BABYLON.Vector2(xmin, ymax)
  82015. ];
  82016. };
  82017. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82018. if (cx === void 0) { cx = 0; }
  82019. if (cy === void 0) { cy = 0; }
  82020. if (numberOfSides === void 0) { numberOfSides = 32; }
  82021. var result = new Array();
  82022. var angle = 0;
  82023. var increment = (Math.PI * 2) / numberOfSides;
  82024. for (var i = 0; i < numberOfSides; i++) {
  82025. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82026. angle -= increment;
  82027. }
  82028. return result;
  82029. };
  82030. Polygon.Parse = function (input) {
  82031. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82032. var i, result = [];
  82033. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82034. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82035. }
  82036. return result;
  82037. };
  82038. Polygon.StartingAt = function (x, y) {
  82039. return BABYLON.Path2.StartingAt(x, y);
  82040. };
  82041. return Polygon;
  82042. }());
  82043. BABYLON.Polygon = Polygon;
  82044. var PolygonMeshBuilder = /** @class */ (function () {
  82045. function PolygonMeshBuilder(name, contours, scene) {
  82046. this._points = new PolygonPoints();
  82047. this._outlinepoints = new PolygonPoints();
  82048. this._holes = new Array();
  82049. this._epoints = new Array();
  82050. this._eholes = new Array();
  82051. this._name = name;
  82052. this._scene = scene;
  82053. var points;
  82054. if (contours instanceof BABYLON.Path2) {
  82055. points = contours.getPoints();
  82056. }
  82057. else {
  82058. points = contours;
  82059. }
  82060. this._addToepoint(points);
  82061. this._points.add(points);
  82062. this._outlinepoints.add(points);
  82063. if (typeof earcut === 'undefined') {
  82064. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82065. }
  82066. }
  82067. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82068. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82069. var p = points_1[_i];
  82070. this._epoints.push(p.x, p.y);
  82071. }
  82072. };
  82073. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82074. this._points.add(hole);
  82075. var holepoints = new PolygonPoints();
  82076. holepoints.add(hole);
  82077. this._holes.push(holepoints);
  82078. this._eholes.push(this._epoints.length / 2);
  82079. this._addToepoint(hole);
  82080. return this;
  82081. };
  82082. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82083. var _this = this;
  82084. if (updatable === void 0) { updatable = false; }
  82085. if (depth === void 0) { depth = 0; }
  82086. var result = new BABYLON.Mesh(this._name, this._scene);
  82087. var normals = new Array();
  82088. var positions = new Array();
  82089. var uvs = new Array();
  82090. var bounds = this._points.computeBounds();
  82091. this._points.elements.forEach(function (p) {
  82092. normals.push(0, 1.0, 0);
  82093. positions.push(p.x, 0, p.y);
  82094. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82095. });
  82096. var indices = new Array();
  82097. var res = earcut(this._epoints, this._eholes, 2);
  82098. for (var i = 0; i < res.length; i++) {
  82099. indices.push(res[i]);
  82100. }
  82101. if (depth > 0) {
  82102. var positionscount = (positions.length / 3); //get the current pointcount
  82103. this._points.elements.forEach(function (p) {
  82104. normals.push(0, -1.0, 0);
  82105. positions.push(p.x, -depth, p.y);
  82106. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82107. });
  82108. var totalCount = indices.length;
  82109. for (var i = 0; i < totalCount; i += 3) {
  82110. var i0 = indices[i + 0];
  82111. var i1 = indices[i + 1];
  82112. var i2 = indices[i + 2];
  82113. indices.push(i2 + positionscount);
  82114. indices.push(i1 + positionscount);
  82115. indices.push(i0 + positionscount);
  82116. }
  82117. //Add the sides
  82118. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82119. this._holes.forEach(function (hole) {
  82120. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82121. });
  82122. }
  82123. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82124. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82125. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82126. result.setIndices(indices);
  82127. return result;
  82128. };
  82129. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82130. var StartIndex = positions.length / 3;
  82131. var ulength = 0;
  82132. for (var i = 0; i < points.elements.length; i++) {
  82133. var p = points.elements[i];
  82134. var p1;
  82135. if ((i + 1) > points.elements.length - 1) {
  82136. p1 = points.elements[0];
  82137. }
  82138. else {
  82139. p1 = points.elements[i + 1];
  82140. }
  82141. positions.push(p.x, 0, p.y);
  82142. positions.push(p.x, -depth, p.y);
  82143. positions.push(p1.x, 0, p1.y);
  82144. positions.push(p1.x, -depth, p1.y);
  82145. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82146. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82147. var v3 = v2.subtract(v1);
  82148. var v4 = new BABYLON.Vector3(0, 1, 0);
  82149. var vn = BABYLON.Vector3.Cross(v3, v4);
  82150. vn = vn.normalize();
  82151. uvs.push(ulength / bounds.width, 0);
  82152. uvs.push(ulength / bounds.width, 1);
  82153. ulength += v3.length();
  82154. uvs.push((ulength / bounds.width), 0);
  82155. uvs.push((ulength / bounds.width), 1);
  82156. if (!flip) {
  82157. normals.push(-vn.x, -vn.y, -vn.z);
  82158. normals.push(-vn.x, -vn.y, -vn.z);
  82159. normals.push(-vn.x, -vn.y, -vn.z);
  82160. normals.push(-vn.x, -vn.y, -vn.z);
  82161. indices.push(StartIndex);
  82162. indices.push(StartIndex + 1);
  82163. indices.push(StartIndex + 2);
  82164. indices.push(StartIndex + 1);
  82165. indices.push(StartIndex + 3);
  82166. indices.push(StartIndex + 2);
  82167. }
  82168. else {
  82169. normals.push(vn.x, vn.y, vn.z);
  82170. normals.push(vn.x, vn.y, vn.z);
  82171. normals.push(vn.x, vn.y, vn.z);
  82172. normals.push(vn.x, vn.y, vn.z);
  82173. indices.push(StartIndex);
  82174. indices.push(StartIndex + 2);
  82175. indices.push(StartIndex + 1);
  82176. indices.push(StartIndex + 1);
  82177. indices.push(StartIndex + 2);
  82178. indices.push(StartIndex + 3);
  82179. }
  82180. StartIndex += 4;
  82181. }
  82182. ;
  82183. };
  82184. return PolygonMeshBuilder;
  82185. }());
  82186. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82187. })(BABYLON || (BABYLON = {}));
  82188. //# sourceMappingURL=babylon.polygonMesh.js.map
  82189. var BABYLON;
  82190. (function (BABYLON) {
  82191. // Unique ID when we import meshes from Babylon to CSG
  82192. var currentCSGMeshId = 0;
  82193. // # class Vertex
  82194. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82195. // one to provide additional features like texture coordinates and vertex
  82196. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82197. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82198. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82199. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82200. // is not used anywhere else.
  82201. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82202. var Vertex = /** @class */ (function () {
  82203. function Vertex(pos, normal, uv) {
  82204. this.pos = pos;
  82205. this.normal = normal;
  82206. this.uv = uv;
  82207. }
  82208. Vertex.prototype.clone = function () {
  82209. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82210. };
  82211. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82212. // orientation of a polygon is flipped.
  82213. Vertex.prototype.flip = function () {
  82214. this.normal = this.normal.scale(-1);
  82215. };
  82216. // Create a new vertex between this vertex and `other` by linearly
  82217. // interpolating all properties using a parameter of `t`. Subclasses should
  82218. // override this to interpolate additional properties.
  82219. Vertex.prototype.interpolate = function (other, t) {
  82220. 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));
  82221. };
  82222. return Vertex;
  82223. }());
  82224. // # class Plane
  82225. // Represents a plane in 3D space.
  82226. var Plane = /** @class */ (function () {
  82227. function Plane(normal, w) {
  82228. this.normal = normal;
  82229. this.w = w;
  82230. }
  82231. Plane.FromPoints = function (a, b, c) {
  82232. var v0 = c.subtract(a);
  82233. var v1 = b.subtract(a);
  82234. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82235. return null;
  82236. }
  82237. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82238. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82239. };
  82240. Plane.prototype.clone = function () {
  82241. return new Plane(this.normal.clone(), this.w);
  82242. };
  82243. Plane.prototype.flip = function () {
  82244. this.normal.scaleInPlace(-1);
  82245. this.w = -this.w;
  82246. };
  82247. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82248. // fragments in the appropriate lists. Coplanar polygons go into either
  82249. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82250. // respect to this plane. Polygons in front or in back of this plane go into
  82251. // either `front` or `back`.
  82252. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82253. var COPLANAR = 0;
  82254. var FRONT = 1;
  82255. var BACK = 2;
  82256. var SPANNING = 3;
  82257. // Classify each point as well as the entire polygon into one of the above
  82258. // four classes.
  82259. var polygonType = 0;
  82260. var types = [];
  82261. var i;
  82262. var t;
  82263. for (i = 0; i < polygon.vertices.length; i++) {
  82264. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82265. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82266. polygonType |= type;
  82267. types.push(type);
  82268. }
  82269. // Put the polygon in the correct list, splitting it when necessary.
  82270. switch (polygonType) {
  82271. case COPLANAR:
  82272. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82273. break;
  82274. case FRONT:
  82275. front.push(polygon);
  82276. break;
  82277. case BACK:
  82278. back.push(polygon);
  82279. break;
  82280. case SPANNING:
  82281. var f = [], b = [];
  82282. for (i = 0; i < polygon.vertices.length; i++) {
  82283. var j = (i + 1) % polygon.vertices.length;
  82284. var ti = types[i], tj = types[j];
  82285. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82286. if (ti !== BACK)
  82287. f.push(vi);
  82288. if (ti !== FRONT)
  82289. b.push(ti !== BACK ? vi.clone() : vi);
  82290. if ((ti | tj) === SPANNING) {
  82291. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82292. var v = vi.interpolate(vj, t);
  82293. f.push(v);
  82294. b.push(v.clone());
  82295. }
  82296. }
  82297. var poly;
  82298. if (f.length >= 3) {
  82299. poly = new Polygon(f, polygon.shared);
  82300. if (poly.plane)
  82301. front.push(poly);
  82302. }
  82303. if (b.length >= 3) {
  82304. poly = new Polygon(b, polygon.shared);
  82305. if (poly.plane)
  82306. back.push(poly);
  82307. }
  82308. break;
  82309. }
  82310. };
  82311. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82312. // point is on the plane.
  82313. Plane.EPSILON = 1e-5;
  82314. return Plane;
  82315. }());
  82316. // # class Polygon
  82317. // Represents a convex polygon. The vertices used to initialize a polygon must
  82318. // be coplanar and form a convex loop.
  82319. //
  82320. // Each convex polygon has a `shared` property, which is shared between all
  82321. // polygons that are clones of each other or were split from the same polygon.
  82322. // This can be used to define per-polygon properties (such as surface color).
  82323. var Polygon = /** @class */ (function () {
  82324. function Polygon(vertices, shared) {
  82325. this.vertices = vertices;
  82326. this.shared = shared;
  82327. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82328. }
  82329. Polygon.prototype.clone = function () {
  82330. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82331. return new Polygon(vertices, this.shared);
  82332. };
  82333. Polygon.prototype.flip = function () {
  82334. this.vertices.reverse().map(function (v) { v.flip(); });
  82335. this.plane.flip();
  82336. };
  82337. return Polygon;
  82338. }());
  82339. // # class Node
  82340. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82341. // by picking a polygon to split along. That polygon (and all other coplanar
  82342. // polygons) are added directly to that node and the other polygons are added to
  82343. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82344. // no distinction between internal and leaf nodes.
  82345. var Node = /** @class */ (function () {
  82346. function Node(polygons) {
  82347. this.plane = null;
  82348. this.front = null;
  82349. this.back = null;
  82350. this.polygons = new Array();
  82351. if (polygons) {
  82352. this.build(polygons);
  82353. }
  82354. }
  82355. Node.prototype.clone = function () {
  82356. var node = new Node();
  82357. node.plane = this.plane && this.plane.clone();
  82358. node.front = this.front && this.front.clone();
  82359. node.back = this.back && this.back.clone();
  82360. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82361. return node;
  82362. };
  82363. // Convert solid space to empty space and empty space to solid space.
  82364. Node.prototype.invert = function () {
  82365. for (var i = 0; i < this.polygons.length; i++) {
  82366. this.polygons[i].flip();
  82367. }
  82368. if (this.plane) {
  82369. this.plane.flip();
  82370. }
  82371. if (this.front) {
  82372. this.front.invert();
  82373. }
  82374. if (this.back) {
  82375. this.back.invert();
  82376. }
  82377. var temp = this.front;
  82378. this.front = this.back;
  82379. this.back = temp;
  82380. };
  82381. // Recursively remove all polygons in `polygons` that are inside this BSP
  82382. // tree.
  82383. Node.prototype.clipPolygons = function (polygons) {
  82384. if (!this.plane)
  82385. return polygons.slice();
  82386. var front = new Array(), back = new Array();
  82387. for (var i = 0; i < polygons.length; i++) {
  82388. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82389. }
  82390. if (this.front) {
  82391. front = this.front.clipPolygons(front);
  82392. }
  82393. if (this.back) {
  82394. back = this.back.clipPolygons(back);
  82395. }
  82396. else {
  82397. back = [];
  82398. }
  82399. return front.concat(back);
  82400. };
  82401. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82402. // `bsp`.
  82403. Node.prototype.clipTo = function (bsp) {
  82404. this.polygons = bsp.clipPolygons(this.polygons);
  82405. if (this.front)
  82406. this.front.clipTo(bsp);
  82407. if (this.back)
  82408. this.back.clipTo(bsp);
  82409. };
  82410. // Return a list of all polygons in this BSP tree.
  82411. Node.prototype.allPolygons = function () {
  82412. var polygons = this.polygons.slice();
  82413. if (this.front)
  82414. polygons = polygons.concat(this.front.allPolygons());
  82415. if (this.back)
  82416. polygons = polygons.concat(this.back.allPolygons());
  82417. return polygons;
  82418. };
  82419. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82420. // new polygons are filtered down to the bottom of the tree and become new
  82421. // nodes there. Each set of polygons is partitioned using the first polygon
  82422. // (no heuristic is used to pick a good split).
  82423. Node.prototype.build = function (polygons) {
  82424. if (!polygons.length)
  82425. return;
  82426. if (!this.plane)
  82427. this.plane = polygons[0].plane.clone();
  82428. var front = new Array(), back = new Array();
  82429. for (var i = 0; i < polygons.length; i++) {
  82430. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82431. }
  82432. if (front.length) {
  82433. if (!this.front)
  82434. this.front = new Node();
  82435. this.front.build(front);
  82436. }
  82437. if (back.length) {
  82438. if (!this.back)
  82439. this.back = new Node();
  82440. this.back.build(back);
  82441. }
  82442. };
  82443. return Node;
  82444. }());
  82445. var CSG = /** @class */ (function () {
  82446. function CSG() {
  82447. this.polygons = new Array();
  82448. }
  82449. // Convert BABYLON.Mesh to BABYLON.CSG
  82450. CSG.FromMesh = function (mesh) {
  82451. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82452. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82453. if (mesh instanceof BABYLON.Mesh) {
  82454. mesh.computeWorldMatrix(true);
  82455. matrix = mesh.getWorldMatrix();
  82456. meshPosition = mesh.position.clone();
  82457. meshRotation = mesh.rotation.clone();
  82458. if (mesh.rotationQuaternion) {
  82459. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82460. }
  82461. meshScaling = mesh.scaling.clone();
  82462. }
  82463. else {
  82464. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82465. }
  82466. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82467. var subMeshes = mesh.subMeshes;
  82468. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82469. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  82470. vertices = [];
  82471. for (var j = 0; j < 3; j++) {
  82472. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  82473. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  82474. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  82475. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  82476. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  82477. vertex = new Vertex(position, normal, uv);
  82478. vertices.push(vertex);
  82479. }
  82480. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  82481. // To handle the case of degenerated triangle
  82482. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  82483. if (polygon.plane)
  82484. polygons.push(polygon);
  82485. }
  82486. }
  82487. var csg = CSG.FromPolygons(polygons);
  82488. csg.matrix = matrix;
  82489. csg.position = meshPosition;
  82490. csg.rotation = meshRotation;
  82491. csg.scaling = meshScaling;
  82492. csg.rotationQuaternion = meshRotationQuaternion;
  82493. currentCSGMeshId++;
  82494. return csg;
  82495. };
  82496. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  82497. CSG.FromPolygons = function (polygons) {
  82498. var csg = new CSG();
  82499. csg.polygons = polygons;
  82500. return csg;
  82501. };
  82502. CSG.prototype.clone = function () {
  82503. var csg = new CSG();
  82504. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  82505. csg.copyTransformAttributes(this);
  82506. return csg;
  82507. };
  82508. CSG.prototype.union = function (csg) {
  82509. var a = new Node(this.clone().polygons);
  82510. var b = new Node(csg.clone().polygons);
  82511. a.clipTo(b);
  82512. b.clipTo(a);
  82513. b.invert();
  82514. b.clipTo(a);
  82515. b.invert();
  82516. a.build(b.allPolygons());
  82517. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82518. };
  82519. CSG.prototype.unionInPlace = function (csg) {
  82520. var a = new Node(this.polygons);
  82521. var b = new Node(csg.polygons);
  82522. a.clipTo(b);
  82523. b.clipTo(a);
  82524. b.invert();
  82525. b.clipTo(a);
  82526. b.invert();
  82527. a.build(b.allPolygons());
  82528. this.polygons = a.allPolygons();
  82529. };
  82530. CSG.prototype.subtract = function (csg) {
  82531. var a = new Node(this.clone().polygons);
  82532. var b = new Node(csg.clone().polygons);
  82533. a.invert();
  82534. a.clipTo(b);
  82535. b.clipTo(a);
  82536. b.invert();
  82537. b.clipTo(a);
  82538. b.invert();
  82539. a.build(b.allPolygons());
  82540. a.invert();
  82541. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82542. };
  82543. CSG.prototype.subtractInPlace = function (csg) {
  82544. var a = new Node(this.polygons);
  82545. var b = new Node(csg.polygons);
  82546. a.invert();
  82547. a.clipTo(b);
  82548. b.clipTo(a);
  82549. b.invert();
  82550. b.clipTo(a);
  82551. b.invert();
  82552. a.build(b.allPolygons());
  82553. a.invert();
  82554. this.polygons = a.allPolygons();
  82555. };
  82556. CSG.prototype.intersect = function (csg) {
  82557. var a = new Node(this.clone().polygons);
  82558. var b = new Node(csg.clone().polygons);
  82559. a.invert();
  82560. b.clipTo(a);
  82561. b.invert();
  82562. a.clipTo(b);
  82563. b.clipTo(a);
  82564. a.build(b.allPolygons());
  82565. a.invert();
  82566. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82567. };
  82568. CSG.prototype.intersectInPlace = function (csg) {
  82569. var a = new Node(this.polygons);
  82570. var b = new Node(csg.polygons);
  82571. a.invert();
  82572. b.clipTo(a);
  82573. b.invert();
  82574. a.clipTo(b);
  82575. b.clipTo(a);
  82576. a.build(b.allPolygons());
  82577. a.invert();
  82578. this.polygons = a.allPolygons();
  82579. };
  82580. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  82581. // not modified.
  82582. CSG.prototype.inverse = function () {
  82583. var csg = this.clone();
  82584. csg.inverseInPlace();
  82585. return csg;
  82586. };
  82587. CSG.prototype.inverseInPlace = function () {
  82588. this.polygons.map(function (p) { p.flip(); });
  82589. };
  82590. // This is used to keep meshes transformations so they can be restored
  82591. // when we build back a Babylon Mesh
  82592. // NB : All CSG operations are performed in world coordinates
  82593. CSG.prototype.copyTransformAttributes = function (csg) {
  82594. this.matrix = csg.matrix;
  82595. this.position = csg.position;
  82596. this.rotation = csg.rotation;
  82597. this.scaling = csg.scaling;
  82598. this.rotationQuaternion = csg.rotationQuaternion;
  82599. return this;
  82600. };
  82601. // Build Raw mesh from CSG
  82602. // Coordinates here are in world space
  82603. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  82604. var matrix = this.matrix.clone();
  82605. matrix.invert();
  82606. 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;
  82607. if (keepSubMeshes) {
  82608. // Sort Polygons, since subMeshes are indices range
  82609. polygons.sort(function (a, b) {
  82610. if (a.shared.meshId === b.shared.meshId) {
  82611. return a.shared.subMeshId - b.shared.subMeshId;
  82612. }
  82613. else {
  82614. return a.shared.meshId - b.shared.meshId;
  82615. }
  82616. });
  82617. }
  82618. for (var i = 0, il = polygons.length; i < il; i++) {
  82619. polygon = polygons[i];
  82620. // Building SubMeshes
  82621. if (!subMesh_dict[polygon.shared.meshId]) {
  82622. subMesh_dict[polygon.shared.meshId] = {};
  82623. }
  82624. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  82625. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  82626. indexStart: +Infinity,
  82627. indexEnd: -Infinity,
  82628. materialIndex: polygon.shared.materialIndex
  82629. };
  82630. }
  82631. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  82632. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  82633. polygonIndices[0] = 0;
  82634. polygonIndices[1] = j - 1;
  82635. polygonIndices[2] = j;
  82636. for (var k = 0; k < 3; k++) {
  82637. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  82638. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  82639. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  82640. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  82641. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  82642. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  82643. // Check if 2 points can be merged
  82644. if (!(typeof vertex_idx !== 'undefined' &&
  82645. normals[vertex_idx * 3] === localNormal.x &&
  82646. normals[vertex_idx * 3 + 1] === localNormal.y &&
  82647. normals[vertex_idx * 3 + 2] === localNormal.z &&
  82648. uvs[vertex_idx * 2] === uv.x &&
  82649. uvs[vertex_idx * 2 + 1] === uv.y)) {
  82650. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  82651. uvs.push(uv.x, uv.y);
  82652. normals.push(normal.x, normal.y, normal.z);
  82653. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  82654. }
  82655. indices.push(vertex_idx);
  82656. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  82657. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  82658. currentIndex++;
  82659. }
  82660. }
  82661. }
  82662. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  82663. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  82664. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  82665. mesh.setIndices(indices, null);
  82666. if (keepSubMeshes) {
  82667. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  82668. var materialIndexOffset = 0, materialMaxIndex;
  82669. mesh.subMeshes = new Array();
  82670. for (var m in subMesh_dict) {
  82671. materialMaxIndex = -1;
  82672. for (var sm in subMesh_dict[m]) {
  82673. subMesh_obj = subMesh_dict[m][sm];
  82674. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  82675. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  82676. }
  82677. materialIndexOffset += ++materialMaxIndex;
  82678. }
  82679. }
  82680. return mesh;
  82681. };
  82682. // Build Mesh from CSG taking material and transforms into account
  82683. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  82684. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  82685. mesh.material = material;
  82686. mesh.position.copyFrom(this.position);
  82687. mesh.rotation.copyFrom(this.rotation);
  82688. if (this.rotationQuaternion) {
  82689. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  82690. }
  82691. mesh.scaling.copyFrom(this.scaling);
  82692. mesh.computeWorldMatrix(true);
  82693. return mesh;
  82694. };
  82695. return CSG;
  82696. }());
  82697. BABYLON.CSG = CSG;
  82698. })(BABYLON || (BABYLON = {}));
  82699. //# sourceMappingURL=babylon.csg.js.map
  82700. var BABYLON;
  82701. (function (BABYLON) {
  82702. var LensFlare = /** @class */ (function () {
  82703. function LensFlare(size, position, color, imgUrl, system) {
  82704. this.size = size;
  82705. this.position = position;
  82706. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  82707. this.color = color || new BABYLON.Color3(1, 1, 1);
  82708. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  82709. this._system = system;
  82710. system.lensFlares.push(this);
  82711. }
  82712. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  82713. return new LensFlare(size, position, color, imgUrl, system);
  82714. };
  82715. LensFlare.prototype.dispose = function () {
  82716. if (this.texture) {
  82717. this.texture.dispose();
  82718. }
  82719. // Remove from scene
  82720. var index = this._system.lensFlares.indexOf(this);
  82721. this._system.lensFlares.splice(index, 1);
  82722. };
  82723. ;
  82724. return LensFlare;
  82725. }());
  82726. BABYLON.LensFlare = LensFlare;
  82727. })(BABYLON || (BABYLON = {}));
  82728. //# sourceMappingURL=babylon.lensFlare.js.map
  82729. var BABYLON;
  82730. (function (BABYLON) {
  82731. var LensFlareSystem = /** @class */ (function () {
  82732. function LensFlareSystem(name, emitter, scene) {
  82733. this.name = name;
  82734. this.lensFlares = new Array();
  82735. this.borderLimit = 300;
  82736. this.viewportBorder = 0;
  82737. this.layerMask = 0x0FFFFFFF;
  82738. this._vertexBuffers = {};
  82739. this._isEnabled = true;
  82740. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82741. this._emitter = emitter;
  82742. this.id = name;
  82743. scene.lensFlareSystems.push(this);
  82744. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  82745. var engine = scene.getEngine();
  82746. // VBO
  82747. var vertices = [];
  82748. vertices.push(1, 1);
  82749. vertices.push(-1, 1);
  82750. vertices.push(-1, -1);
  82751. vertices.push(1, -1);
  82752. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82753. // Indices
  82754. var indices = [];
  82755. indices.push(0);
  82756. indices.push(1);
  82757. indices.push(2);
  82758. indices.push(0);
  82759. indices.push(2);
  82760. indices.push(3);
  82761. this._indexBuffer = engine.createIndexBuffer(indices);
  82762. // Effects
  82763. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  82764. }
  82765. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  82766. get: function () {
  82767. return this._isEnabled;
  82768. },
  82769. set: function (value) {
  82770. this._isEnabled = value;
  82771. },
  82772. enumerable: true,
  82773. configurable: true
  82774. });
  82775. LensFlareSystem.prototype.getScene = function () {
  82776. return this._scene;
  82777. };
  82778. LensFlareSystem.prototype.getEmitter = function () {
  82779. return this._emitter;
  82780. };
  82781. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  82782. this._emitter = newEmitter;
  82783. };
  82784. LensFlareSystem.prototype.getEmitterPosition = function () {
  82785. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  82786. };
  82787. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  82788. var position = this.getEmitterPosition();
  82789. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  82790. this._positionX = position.x;
  82791. this._positionY = position.y;
  82792. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  82793. if (this.viewportBorder > 0) {
  82794. globalViewport.x -= this.viewportBorder;
  82795. globalViewport.y -= this.viewportBorder;
  82796. globalViewport.width += this.viewportBorder * 2;
  82797. globalViewport.height += this.viewportBorder * 2;
  82798. position.x += this.viewportBorder;
  82799. position.y += this.viewportBorder;
  82800. this._positionX += this.viewportBorder;
  82801. this._positionY += this.viewportBorder;
  82802. }
  82803. if (position.z > 0) {
  82804. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82805. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82806. return true;
  82807. }
  82808. return true;
  82809. }
  82810. return false;
  82811. };
  82812. LensFlareSystem.prototype._isVisible = function () {
  82813. if (!this._isEnabled || !this._scene.activeCamera) {
  82814. return false;
  82815. }
  82816. var emitterPosition = this.getEmitterPosition();
  82817. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82818. var distance = direction.length();
  82819. direction.normalize();
  82820. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82821. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82822. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82823. };
  82824. LensFlareSystem.prototype.render = function () {
  82825. if (!this._effect.isReady() || !this._scene.activeCamera)
  82826. return false;
  82827. var engine = this._scene.getEngine();
  82828. var viewport = this._scene.activeCamera.viewport;
  82829. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82830. // Position
  82831. if (!this.computeEffectivePosition(globalViewport)) {
  82832. return false;
  82833. }
  82834. // Visibility
  82835. if (!this._isVisible()) {
  82836. return false;
  82837. }
  82838. // Intensity
  82839. var awayX;
  82840. var awayY;
  82841. if (this._positionX < this.borderLimit + globalViewport.x) {
  82842. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82843. }
  82844. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82845. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82846. }
  82847. else {
  82848. awayX = 0;
  82849. }
  82850. if (this._positionY < this.borderLimit + globalViewport.y) {
  82851. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82852. }
  82853. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82854. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82855. }
  82856. else {
  82857. awayY = 0;
  82858. }
  82859. var away = (awayX > awayY) ? awayX : awayY;
  82860. away -= this.viewportBorder;
  82861. if (away > this.borderLimit) {
  82862. away = this.borderLimit;
  82863. }
  82864. var intensity = 1.0 - (away / this.borderLimit);
  82865. if (intensity < 0) {
  82866. return false;
  82867. }
  82868. if (intensity > 1.0) {
  82869. intensity = 1.0;
  82870. }
  82871. if (this.viewportBorder > 0) {
  82872. globalViewport.x += this.viewportBorder;
  82873. globalViewport.y += this.viewportBorder;
  82874. globalViewport.width -= this.viewportBorder * 2;
  82875. globalViewport.height -= this.viewportBorder * 2;
  82876. this._positionX -= this.viewportBorder;
  82877. this._positionY -= this.viewportBorder;
  82878. }
  82879. // Position
  82880. var centerX = globalViewport.x + globalViewport.width / 2;
  82881. var centerY = globalViewport.y + globalViewport.height / 2;
  82882. var distX = centerX - this._positionX;
  82883. var distY = centerY - this._positionY;
  82884. // Effects
  82885. engine.enableEffect(this._effect);
  82886. engine.setState(false);
  82887. engine.setDepthBuffer(false);
  82888. // VBOs
  82889. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82890. // Flares
  82891. for (var index = 0; index < this.lensFlares.length; index++) {
  82892. var flare = this.lensFlares[index];
  82893. engine.setAlphaMode(flare.alphaMode);
  82894. var x = centerX - (distX * flare.position);
  82895. var y = centerY - (distY * flare.position);
  82896. var cw = flare.size;
  82897. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82898. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82899. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82900. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82901. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82902. // Texture
  82903. this._effect.setTexture("textureSampler", flare.texture);
  82904. // Color
  82905. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82906. // Draw order
  82907. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82908. }
  82909. engine.setDepthBuffer(true);
  82910. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82911. return true;
  82912. };
  82913. LensFlareSystem.prototype.dispose = function () {
  82914. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82915. if (vertexBuffer) {
  82916. vertexBuffer.dispose();
  82917. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82918. }
  82919. if (this._indexBuffer) {
  82920. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82921. this._indexBuffer = null;
  82922. }
  82923. while (this.lensFlares.length) {
  82924. this.lensFlares[0].dispose();
  82925. }
  82926. // Remove from scene
  82927. var index = this._scene.lensFlareSystems.indexOf(this);
  82928. this._scene.lensFlareSystems.splice(index, 1);
  82929. };
  82930. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82931. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82932. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82933. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82934. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82935. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82936. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82937. var parsedFlare = parsedLensFlareSystem.flares[index];
  82938. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82939. }
  82940. return lensFlareSystem;
  82941. };
  82942. LensFlareSystem.prototype.serialize = function () {
  82943. var serializationObject = {};
  82944. serializationObject.id = this.id;
  82945. serializationObject.name = this.name;
  82946. serializationObject.emitterId = this.getEmitter().id;
  82947. serializationObject.borderLimit = this.borderLimit;
  82948. serializationObject.flares = [];
  82949. for (var index = 0; index < this.lensFlares.length; index++) {
  82950. var flare = this.lensFlares[index];
  82951. serializationObject.flares.push({
  82952. size: flare.size,
  82953. position: flare.position,
  82954. color: flare.color.asArray(),
  82955. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82956. });
  82957. }
  82958. return serializationObject;
  82959. };
  82960. return LensFlareSystem;
  82961. }());
  82962. BABYLON.LensFlareSystem = LensFlareSystem;
  82963. })(BABYLON || (BABYLON = {}));
  82964. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82965. var BABYLON;
  82966. (function (BABYLON) {
  82967. /**
  82968. * This is a holder class for the physics joint created by the physics plugin.
  82969. * It holds a set of functions to control the underlying joint.
  82970. */
  82971. var PhysicsJoint = /** @class */ (function () {
  82972. function PhysicsJoint(type, jointData) {
  82973. this.type = type;
  82974. this.jointData = jointData;
  82975. jointData.nativeParams = jointData.nativeParams || {};
  82976. }
  82977. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82978. get: function () {
  82979. return this._physicsJoint;
  82980. },
  82981. set: function (newJoint) {
  82982. if (this._physicsJoint) {
  82983. //remove from the wolrd
  82984. }
  82985. this._physicsJoint = newJoint;
  82986. },
  82987. enumerable: true,
  82988. configurable: true
  82989. });
  82990. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82991. set: function (physicsPlugin) {
  82992. this._physicsPlugin = physicsPlugin;
  82993. },
  82994. enumerable: true,
  82995. configurable: true
  82996. });
  82997. /**
  82998. * Execute a function that is physics-plugin specific.
  82999. * @param {Function} func the function that will be executed.
  83000. * It accepts two parameters: the physics world and the physics joint.
  83001. */
  83002. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83003. func(this._physicsPlugin.world, this._physicsJoint);
  83004. };
  83005. //TODO check if the native joints are the same
  83006. //Joint Types
  83007. PhysicsJoint.DistanceJoint = 0;
  83008. PhysicsJoint.HingeJoint = 1;
  83009. PhysicsJoint.BallAndSocketJoint = 2;
  83010. PhysicsJoint.WheelJoint = 3;
  83011. PhysicsJoint.SliderJoint = 4;
  83012. //OIMO
  83013. PhysicsJoint.PrismaticJoint = 5;
  83014. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83015. PhysicsJoint.UniversalJoint = 6;
  83016. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83017. //Cannon
  83018. //Similar to a Ball-Joint. Different in params
  83019. PhysicsJoint.PointToPointJoint = 8;
  83020. //Cannon only at the moment
  83021. PhysicsJoint.SpringJoint = 9;
  83022. PhysicsJoint.LockJoint = 10;
  83023. return PhysicsJoint;
  83024. }());
  83025. BABYLON.PhysicsJoint = PhysicsJoint;
  83026. /**
  83027. * A class representing a physics distance joint.
  83028. */
  83029. var DistanceJoint = /** @class */ (function (_super) {
  83030. __extends(DistanceJoint, _super);
  83031. function DistanceJoint(jointData) {
  83032. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83033. }
  83034. /**
  83035. * Update the predefined distance.
  83036. */
  83037. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83038. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83039. };
  83040. return DistanceJoint;
  83041. }(PhysicsJoint));
  83042. BABYLON.DistanceJoint = DistanceJoint;
  83043. var MotorEnabledJoint = /** @class */ (function (_super) {
  83044. __extends(MotorEnabledJoint, _super);
  83045. function MotorEnabledJoint(type, jointData) {
  83046. return _super.call(this, type, jointData) || this;
  83047. }
  83048. /**
  83049. * Set the motor values.
  83050. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83051. * @param {number} force the force to apply
  83052. * @param {number} maxForce max force for this motor.
  83053. */
  83054. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83055. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83056. };
  83057. /**
  83058. * Set the motor's limits.
  83059. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83060. */
  83061. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83062. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83063. };
  83064. return MotorEnabledJoint;
  83065. }(PhysicsJoint));
  83066. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83067. /**
  83068. * This class represents a single hinge physics joint
  83069. */
  83070. var HingeJoint = /** @class */ (function (_super) {
  83071. __extends(HingeJoint, _super);
  83072. function HingeJoint(jointData) {
  83073. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83074. }
  83075. /**
  83076. * Set the motor values.
  83077. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83078. * @param {number} force the force to apply
  83079. * @param {number} maxForce max force for this motor.
  83080. */
  83081. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83082. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83083. };
  83084. /**
  83085. * Set the motor's limits.
  83086. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83087. */
  83088. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83089. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83090. };
  83091. return HingeJoint;
  83092. }(MotorEnabledJoint));
  83093. BABYLON.HingeJoint = HingeJoint;
  83094. /**
  83095. * This class represents a dual hinge physics joint (same as wheel joint)
  83096. */
  83097. var Hinge2Joint = /** @class */ (function (_super) {
  83098. __extends(Hinge2Joint, _super);
  83099. function Hinge2Joint(jointData) {
  83100. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83101. }
  83102. /**
  83103. * Set the motor values.
  83104. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83105. * @param {number} force the force to apply
  83106. * @param {number} maxForce max force for this motor.
  83107. * @param {motorIndex} the motor's index, 0 or 1.
  83108. */
  83109. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83110. if (motorIndex === void 0) { motorIndex = 0; }
  83111. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83112. };
  83113. /**
  83114. * Set the motor limits.
  83115. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83116. * @param {number} upperLimit the upper limit
  83117. * @param {number} lowerLimit lower limit
  83118. * @param {motorIndex} the motor's index, 0 or 1.
  83119. */
  83120. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83121. if (motorIndex === void 0) { motorIndex = 0; }
  83122. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83123. };
  83124. return Hinge2Joint;
  83125. }(MotorEnabledJoint));
  83126. BABYLON.Hinge2Joint = Hinge2Joint;
  83127. })(BABYLON || (BABYLON = {}));
  83128. //# sourceMappingURL=babylon.physicsJoint.js.map
  83129. var BABYLON;
  83130. (function (BABYLON) {
  83131. var PhysicsImpostor = /** @class */ (function () {
  83132. function PhysicsImpostor(object, type, _options, _scene) {
  83133. if (_options === void 0) { _options = { mass: 0 }; }
  83134. var _this = this;
  83135. this.object = object;
  83136. this.type = type;
  83137. this._options = _options;
  83138. this._scene = _scene;
  83139. this._bodyUpdateRequired = false;
  83140. this._onBeforePhysicsStepCallbacks = new Array();
  83141. this._onAfterPhysicsStepCallbacks = new Array();
  83142. this._onPhysicsCollideCallbacks = [];
  83143. this._deltaPosition = BABYLON.Vector3.Zero();
  83144. this._isDisposed = false;
  83145. //temp variables for parent rotation calculations
  83146. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83147. this._tmpQuat = new BABYLON.Quaternion();
  83148. this._tmpQuat2 = new BABYLON.Quaternion();
  83149. /**
  83150. * this function is executed by the physics engine.
  83151. */
  83152. this.beforeStep = function () {
  83153. if (!_this._physicsEngine) {
  83154. return;
  83155. }
  83156. _this.object.translate(_this._deltaPosition, -1);
  83157. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83158. _this.object.computeWorldMatrix(false);
  83159. if (_this.object.parent && _this.object.rotationQuaternion) {
  83160. _this.getParentsRotation();
  83161. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83162. }
  83163. else {
  83164. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83165. }
  83166. if (!_this._options.disableBidirectionalTransformation) {
  83167. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83168. }
  83169. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83170. func(_this);
  83171. });
  83172. };
  83173. /**
  83174. * this function is executed by the physics engine.
  83175. */
  83176. this.afterStep = function () {
  83177. if (!_this._physicsEngine) {
  83178. return;
  83179. }
  83180. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83181. func(_this);
  83182. });
  83183. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83184. // object has now its world rotation. needs to be converted to local.
  83185. if (_this.object.parent && _this.object.rotationQuaternion) {
  83186. _this.getParentsRotation();
  83187. _this._tmpQuat.conjugateInPlace();
  83188. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83189. }
  83190. // take the position set and make it the absolute position of this object.
  83191. _this.object.setAbsolutePosition(_this.object.position);
  83192. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83193. _this.object.translate(_this._deltaPosition, 1);
  83194. };
  83195. /**
  83196. * Legacy collision detection event support
  83197. */
  83198. this.onCollideEvent = null;
  83199. //event and body object due to cannon's event-based architecture.
  83200. this.onCollide = function (e) {
  83201. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83202. return;
  83203. }
  83204. if (!_this._physicsEngine) {
  83205. return;
  83206. }
  83207. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83208. if (otherImpostor) {
  83209. // Legacy collision detection event support
  83210. if (_this.onCollideEvent) {
  83211. _this.onCollideEvent(_this, otherImpostor);
  83212. }
  83213. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83214. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83215. }).forEach(function (obj) {
  83216. obj.callback(_this, otherImpostor);
  83217. });
  83218. }
  83219. };
  83220. //sanity check!
  83221. if (!this.object) {
  83222. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83223. return;
  83224. }
  83225. //legacy support for old syntax.
  83226. if (!this._scene && object.getScene) {
  83227. this._scene = object.getScene();
  83228. }
  83229. if (!this._scene) {
  83230. return;
  83231. }
  83232. this._physicsEngine = this._scene.getPhysicsEngine();
  83233. if (!this._physicsEngine) {
  83234. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83235. }
  83236. else {
  83237. //set the object's quaternion, if not set
  83238. if (!this.object.rotationQuaternion) {
  83239. if (this.object.rotation) {
  83240. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83241. }
  83242. else {
  83243. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83244. }
  83245. }
  83246. //default options params
  83247. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83248. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83249. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83250. this._joints = [];
  83251. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83252. if (!this.object.parent || this._options.ignoreParent) {
  83253. this._init();
  83254. }
  83255. else if (this.object.parent.physicsImpostor) {
  83256. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83257. }
  83258. }
  83259. }
  83260. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83261. get: function () {
  83262. return this._isDisposed;
  83263. },
  83264. enumerable: true,
  83265. configurable: true
  83266. });
  83267. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83268. get: function () {
  83269. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83270. },
  83271. set: function (value) {
  83272. this.setMass(value);
  83273. },
  83274. enumerable: true,
  83275. configurable: true
  83276. });
  83277. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83278. get: function () {
  83279. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83280. },
  83281. set: function (value) {
  83282. if (!this._physicsEngine) {
  83283. return;
  83284. }
  83285. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83286. },
  83287. enumerable: true,
  83288. configurable: true
  83289. });
  83290. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83291. get: function () {
  83292. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83293. },
  83294. set: function (value) {
  83295. if (!this._physicsEngine) {
  83296. return;
  83297. }
  83298. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83299. },
  83300. enumerable: true,
  83301. configurable: true
  83302. });
  83303. /**
  83304. * This function will completly initialize this impostor.
  83305. * It will create a new body - but only if this mesh has no parent.
  83306. * If it has, this impostor will not be used other than to define the impostor
  83307. * of the child mesh.
  83308. */
  83309. PhysicsImpostor.prototype._init = function () {
  83310. if (!this._physicsEngine) {
  83311. return;
  83312. }
  83313. this._physicsEngine.removeImpostor(this);
  83314. this.physicsBody = null;
  83315. this._parent = this._parent || this._getPhysicsParent();
  83316. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83317. this._physicsEngine.addImpostor(this);
  83318. }
  83319. };
  83320. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83321. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83322. var parentMesh = this.object.parent;
  83323. return parentMesh.physicsImpostor;
  83324. }
  83325. return null;
  83326. };
  83327. /**
  83328. * Should a new body be generated.
  83329. */
  83330. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83331. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83332. };
  83333. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83334. this.forceUpdate();
  83335. };
  83336. /**
  83337. * Force a regeneration of this or the parent's impostor's body.
  83338. * Use under cautious - This will remove all joints already implemented.
  83339. */
  83340. PhysicsImpostor.prototype.forceUpdate = function () {
  83341. this._init();
  83342. if (this.parent && !this._options.ignoreParent) {
  83343. this.parent.forceUpdate();
  83344. }
  83345. };
  83346. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83347. /*public get mesh(): AbstractMesh {
  83348. return this._mesh;
  83349. }*/
  83350. /**
  83351. * Gets the body that holds this impostor. Either its own, or its parent.
  83352. */
  83353. get: function () {
  83354. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83355. },
  83356. /**
  83357. * Set the physics body. Used mainly by the physics engine/plugin
  83358. */
  83359. set: function (physicsBody) {
  83360. if (this._physicsBody && this._physicsEngine) {
  83361. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83362. }
  83363. this._physicsBody = physicsBody;
  83364. this.resetUpdateFlags();
  83365. },
  83366. enumerable: true,
  83367. configurable: true
  83368. });
  83369. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83370. get: function () {
  83371. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83372. },
  83373. set: function (value) {
  83374. this._parent = value;
  83375. },
  83376. enumerable: true,
  83377. configurable: true
  83378. });
  83379. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83380. this._bodyUpdateRequired = false;
  83381. };
  83382. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83383. if (this.object.getBoundingInfo) {
  83384. var q = this.object.rotationQuaternion;
  83385. //reset rotation
  83386. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83387. //calculate the world matrix with no rotation
  83388. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83389. var boundingInfo = this.object.getBoundingInfo();
  83390. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83391. //bring back the rotation
  83392. this.object.rotationQuaternion = q;
  83393. //calculate the world matrix with the new rotation
  83394. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83395. return size;
  83396. }
  83397. else {
  83398. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83399. }
  83400. };
  83401. PhysicsImpostor.prototype.getObjectCenter = function () {
  83402. if (this.object.getBoundingInfo) {
  83403. var boundingInfo = this.object.getBoundingInfo();
  83404. return boundingInfo.boundingBox.centerWorld;
  83405. }
  83406. else {
  83407. return this.object.position;
  83408. }
  83409. };
  83410. /**
  83411. * Get a specific parametes from the options parameter.
  83412. */
  83413. PhysicsImpostor.prototype.getParam = function (paramName) {
  83414. return this._options[paramName];
  83415. };
  83416. /**
  83417. * Sets a specific parameter in the options given to the physics plugin
  83418. */
  83419. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83420. this._options[paramName] = value;
  83421. this._bodyUpdateRequired = true;
  83422. };
  83423. /**
  83424. * Specifically change the body's mass option. Won't recreate the physics body object
  83425. */
  83426. PhysicsImpostor.prototype.setMass = function (mass) {
  83427. if (this.getParam("mass") !== mass) {
  83428. this.setParam("mass", mass);
  83429. }
  83430. if (this._physicsEngine) {
  83431. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83432. }
  83433. };
  83434. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83435. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83436. };
  83437. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83438. if (this._physicsEngine) {
  83439. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83440. }
  83441. };
  83442. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83443. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83444. };
  83445. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83446. if (this._physicsEngine) {
  83447. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83448. }
  83449. };
  83450. /**
  83451. * Execute a function with the physics plugin native code.
  83452. * Provide a function the will have two variables - the world object and the physics body object.
  83453. */
  83454. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83455. if (this._physicsEngine) {
  83456. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83457. }
  83458. };
  83459. /**
  83460. * Register a function that will be executed before the physics world is stepping forward.
  83461. */
  83462. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83463. this._onBeforePhysicsStepCallbacks.push(func);
  83464. };
  83465. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83466. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83467. if (index > -1) {
  83468. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83469. }
  83470. else {
  83471. BABYLON.Tools.Warn("Function to remove was not found");
  83472. }
  83473. };
  83474. /**
  83475. * Register a function that will be executed after the physics step
  83476. */
  83477. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  83478. this._onAfterPhysicsStepCallbacks.push(func);
  83479. };
  83480. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  83481. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  83482. if (index > -1) {
  83483. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  83484. }
  83485. else {
  83486. BABYLON.Tools.Warn("Function to remove was not found");
  83487. }
  83488. };
  83489. /**
  83490. * register a function that will be executed when this impostor collides against a different body.
  83491. */
  83492. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  83493. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83494. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  83495. };
  83496. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  83497. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83498. var index = -1;
  83499. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  83500. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  83501. // chcek the arrays match
  83502. var sameList = cbDef.otherImpostors.every(function (impostor) {
  83503. return collidedAgainstList.indexOf(impostor) > -1;
  83504. });
  83505. if (sameList) {
  83506. index = idx;
  83507. }
  83508. return sameList;
  83509. }
  83510. return false;
  83511. });
  83512. if (found) {
  83513. this._onPhysicsCollideCallbacks.splice(index, 1);
  83514. }
  83515. else {
  83516. BABYLON.Tools.Warn("Function to remove was not found");
  83517. }
  83518. };
  83519. PhysicsImpostor.prototype.getParentsRotation = function () {
  83520. var parent = this.object.parent;
  83521. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  83522. while (parent) {
  83523. if (parent.rotationQuaternion) {
  83524. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  83525. }
  83526. else {
  83527. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  83528. }
  83529. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  83530. parent = parent.parent;
  83531. }
  83532. return this._tmpQuat;
  83533. };
  83534. /**
  83535. * Apply a force
  83536. */
  83537. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  83538. if (this._physicsEngine) {
  83539. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  83540. }
  83541. return this;
  83542. };
  83543. /**
  83544. * Apply an impulse
  83545. */
  83546. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  83547. if (this._physicsEngine) {
  83548. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  83549. }
  83550. return this;
  83551. };
  83552. /**
  83553. * A help function to create a joint.
  83554. */
  83555. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  83556. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  83557. this.addJoint(otherImpostor, joint);
  83558. return this;
  83559. };
  83560. /**
  83561. * Add a joint to this impostor with a different impostor.
  83562. */
  83563. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  83564. this._joints.push({
  83565. otherImpostor: otherImpostor,
  83566. joint: joint
  83567. });
  83568. if (this._physicsEngine) {
  83569. this._physicsEngine.addJoint(this, otherImpostor, joint);
  83570. }
  83571. return this;
  83572. };
  83573. /**
  83574. * Will keep this body still, in a sleep mode.
  83575. */
  83576. PhysicsImpostor.prototype.sleep = function () {
  83577. if (this._physicsEngine) {
  83578. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  83579. }
  83580. return this;
  83581. };
  83582. /**
  83583. * Wake the body up.
  83584. */
  83585. PhysicsImpostor.prototype.wakeUp = function () {
  83586. if (this._physicsEngine) {
  83587. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  83588. }
  83589. return this;
  83590. };
  83591. PhysicsImpostor.prototype.clone = function (newObject) {
  83592. if (!newObject)
  83593. return null;
  83594. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  83595. };
  83596. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  83597. var _this = this;
  83598. //no dispose if no physics engine is available.
  83599. if (!this._physicsEngine) {
  83600. return;
  83601. }
  83602. this._joints.forEach(function (j) {
  83603. if (_this._physicsEngine) {
  83604. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  83605. }
  83606. });
  83607. //dispose the physics body
  83608. this._physicsEngine.removeImpostor(this);
  83609. if (this.parent) {
  83610. this.parent.forceUpdate();
  83611. }
  83612. else {
  83613. /*this._object.getChildMeshes().forEach(function(mesh) {
  83614. if (mesh.physicsImpostor) {
  83615. if (disposeChildren) {
  83616. mesh.physicsImpostor.dispose();
  83617. mesh.physicsImpostor = null;
  83618. }
  83619. }
  83620. })*/
  83621. }
  83622. this._isDisposed = true;
  83623. };
  83624. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  83625. this._deltaPosition.copyFrom(position);
  83626. };
  83627. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  83628. if (!this._deltaRotation) {
  83629. this._deltaRotation = new BABYLON.Quaternion();
  83630. }
  83631. this._deltaRotation.copyFrom(rotation);
  83632. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  83633. };
  83634. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  83635. if (this._physicsEngine) {
  83636. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  83637. }
  83638. return this;
  83639. };
  83640. PhysicsImpostor.prototype.getRadius = function () {
  83641. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  83642. };
  83643. /**
  83644. * Sync a bone with this impostor
  83645. * @param bone The bone to sync to the impostor.
  83646. * @param boneMesh The mesh that the bone is influencing.
  83647. * @param jointPivot The pivot of the joint / bone in local space.
  83648. * @param distToJoint Optional distance from the impostor to the joint.
  83649. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83650. */
  83651. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  83652. var tempVec = PhysicsImpostor._tmpVecs[0];
  83653. var mesh = this.object;
  83654. if (mesh.rotationQuaternion) {
  83655. if (adjustRotation) {
  83656. var tempQuat = PhysicsImpostor._tmpQuat;
  83657. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  83658. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  83659. }
  83660. else {
  83661. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  83662. }
  83663. }
  83664. tempVec.x = 0;
  83665. tempVec.y = 0;
  83666. tempVec.z = 0;
  83667. if (jointPivot) {
  83668. tempVec.x = jointPivot.x;
  83669. tempVec.y = jointPivot.y;
  83670. tempVec.z = jointPivot.z;
  83671. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  83672. if (distToJoint === undefined || distToJoint === null) {
  83673. distToJoint = jointPivot.length();
  83674. }
  83675. tempVec.x *= distToJoint;
  83676. tempVec.y *= distToJoint;
  83677. tempVec.z *= distToJoint;
  83678. }
  83679. if (bone.getParent()) {
  83680. tempVec.addInPlace(mesh.getAbsolutePosition());
  83681. bone.setAbsolutePosition(tempVec, boneMesh);
  83682. }
  83683. else {
  83684. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  83685. boneMesh.position.x -= tempVec.x;
  83686. boneMesh.position.y -= tempVec.y;
  83687. boneMesh.position.z -= tempVec.z;
  83688. }
  83689. };
  83690. /**
  83691. * Sync impostor to a bone
  83692. * @param bone The bone that the impostor will be synced to.
  83693. * @param boneMesh The mesh that the bone is influencing.
  83694. * @param jointPivot The pivot of the joint / bone in local space.
  83695. * @param distToJoint Optional distance from the impostor to the joint.
  83696. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83697. * @param boneAxis Optional vector3 axis the bone is aligned with
  83698. */
  83699. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  83700. var mesh = this.object;
  83701. if (mesh.rotationQuaternion) {
  83702. if (adjustRotation) {
  83703. var tempQuat = PhysicsImpostor._tmpQuat;
  83704. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  83705. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  83706. }
  83707. else {
  83708. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  83709. }
  83710. }
  83711. var pos = PhysicsImpostor._tmpVecs[0];
  83712. var boneDir = PhysicsImpostor._tmpVecs[1];
  83713. if (!boneAxis) {
  83714. boneAxis = PhysicsImpostor._tmpVecs[2];
  83715. boneAxis.x = 0;
  83716. boneAxis.y = 1;
  83717. boneAxis.z = 0;
  83718. }
  83719. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  83720. bone.getAbsolutePositionToRef(boneMesh, pos);
  83721. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  83722. distToJoint = jointPivot.length();
  83723. }
  83724. if (distToJoint !== undefined && distToJoint !== null) {
  83725. pos.x += boneDir.x * distToJoint;
  83726. pos.y += boneDir.y * distToJoint;
  83727. pos.z += boneDir.z * distToJoint;
  83728. }
  83729. mesh.setAbsolutePosition(pos);
  83730. };
  83731. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  83732. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  83733. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83734. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  83735. //Impostor types
  83736. PhysicsImpostor.NoImpostor = 0;
  83737. PhysicsImpostor.SphereImpostor = 1;
  83738. PhysicsImpostor.BoxImpostor = 2;
  83739. PhysicsImpostor.PlaneImpostor = 3;
  83740. PhysicsImpostor.MeshImpostor = 4;
  83741. PhysicsImpostor.CylinderImpostor = 7;
  83742. PhysicsImpostor.ParticleImpostor = 8;
  83743. PhysicsImpostor.HeightmapImpostor = 9;
  83744. return PhysicsImpostor;
  83745. }());
  83746. BABYLON.PhysicsImpostor = PhysicsImpostor;
  83747. })(BABYLON || (BABYLON = {}));
  83748. //# sourceMappingURL=babylon.physicsImpostor.js.map
  83749. var BABYLON;
  83750. (function (BABYLON) {
  83751. var PhysicsEngine = /** @class */ (function () {
  83752. function PhysicsEngine(gravity, _physicsPlugin) {
  83753. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  83754. this._physicsPlugin = _physicsPlugin;
  83755. //new methods and parameters
  83756. this._impostors = [];
  83757. this._joints = [];
  83758. if (!this._physicsPlugin.isSupported()) {
  83759. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  83760. + "Please make sure it is included.");
  83761. }
  83762. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  83763. this.setGravity(gravity);
  83764. this.setTimeStep();
  83765. }
  83766. PhysicsEngine.prototype.setGravity = function (gravity) {
  83767. this.gravity = gravity;
  83768. this._physicsPlugin.setGravity(this.gravity);
  83769. };
  83770. /**
  83771. * Set the time step of the physics engine.
  83772. * default is 1/60.
  83773. * To slow it down, enter 1/600 for example.
  83774. * To speed it up, 1/30
  83775. * @param {number} newTimeStep the new timestep to apply to this world.
  83776. */
  83777. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  83778. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  83779. this._physicsPlugin.setTimeStep(newTimeStep);
  83780. };
  83781. /**
  83782. * Get the time step of the physics engine.
  83783. */
  83784. PhysicsEngine.prototype.getTimeStep = function () {
  83785. return this._physicsPlugin.getTimeStep();
  83786. };
  83787. PhysicsEngine.prototype.dispose = function () {
  83788. this._impostors.forEach(function (impostor) {
  83789. impostor.dispose();
  83790. });
  83791. this._physicsPlugin.dispose();
  83792. };
  83793. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83794. return this._physicsPlugin.name;
  83795. };
  83796. /**
  83797. * Adding a new impostor for the impostor tracking.
  83798. * This will be done by the impostor itself.
  83799. * @param {PhysicsImpostor} impostor the impostor to add
  83800. */
  83801. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83802. impostor.uniqueId = this._impostors.push(impostor);
  83803. //if no parent, generate the body
  83804. if (!impostor.parent) {
  83805. this._physicsPlugin.generatePhysicsBody(impostor);
  83806. }
  83807. };
  83808. /**
  83809. * Remove an impostor from the engine.
  83810. * This impostor and its mesh will not longer be updated by the physics engine.
  83811. * @param {PhysicsImpostor} impostor the impostor to remove
  83812. */
  83813. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83814. var index = this._impostors.indexOf(impostor);
  83815. if (index > -1) {
  83816. var removed = this._impostors.splice(index, 1);
  83817. //Is it needed?
  83818. if (removed.length) {
  83819. //this will also remove it from the world.
  83820. removed[0].physicsBody = null;
  83821. }
  83822. }
  83823. };
  83824. /**
  83825. * Add a joint to the physics engine
  83826. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83827. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83828. * @param {PhysicsJoint} the joint that will connect both impostors.
  83829. */
  83830. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83831. var impostorJoint = {
  83832. mainImpostor: mainImpostor,
  83833. connectedImpostor: connectedImpostor,
  83834. joint: joint
  83835. };
  83836. joint.physicsPlugin = this._physicsPlugin;
  83837. this._joints.push(impostorJoint);
  83838. this._physicsPlugin.generateJoint(impostorJoint);
  83839. };
  83840. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83841. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83842. return (impostorJoint.connectedImpostor === connectedImpostor
  83843. && impostorJoint.joint === joint
  83844. && impostorJoint.mainImpostor === mainImpostor);
  83845. });
  83846. if (matchingJoints.length) {
  83847. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83848. //TODO remove it from the list as well
  83849. }
  83850. };
  83851. /**
  83852. * Called by the scene. no need to call it.
  83853. */
  83854. PhysicsEngine.prototype._step = function (delta) {
  83855. var _this = this;
  83856. //check if any mesh has no body / requires an update
  83857. this._impostors.forEach(function (impostor) {
  83858. if (impostor.isBodyInitRequired()) {
  83859. _this._physicsPlugin.generatePhysicsBody(impostor);
  83860. }
  83861. });
  83862. if (delta > 0.1) {
  83863. delta = 0.1;
  83864. }
  83865. else if (delta <= 0) {
  83866. delta = 1.0 / 60.0;
  83867. }
  83868. this._physicsPlugin.executeStep(delta, this._impostors);
  83869. };
  83870. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83871. return this._physicsPlugin;
  83872. };
  83873. PhysicsEngine.prototype.getImpostors = function () {
  83874. return this._impostors;
  83875. };
  83876. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83877. for (var i = 0; i < this._impostors.length; ++i) {
  83878. if (this._impostors[i].object === object) {
  83879. return this._impostors[i];
  83880. }
  83881. }
  83882. return null;
  83883. };
  83884. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83885. for (var i = 0; i < this._impostors.length; ++i) {
  83886. if (this._impostors[i].physicsBody === body) {
  83887. return this._impostors[i];
  83888. }
  83889. }
  83890. return null;
  83891. };
  83892. // Statics
  83893. PhysicsEngine.Epsilon = 0.001;
  83894. return PhysicsEngine;
  83895. }());
  83896. BABYLON.PhysicsEngine = PhysicsEngine;
  83897. })(BABYLON || (BABYLON = {}));
  83898. //# sourceMappingURL=babylon.physicsEngine.js.map
  83899. var BABYLON;
  83900. (function (BABYLON) {
  83901. var PhysicsHelper = /** @class */ (function () {
  83902. function PhysicsHelper(scene) {
  83903. this._scene = scene;
  83904. this._physicsEngine = this._scene.getPhysicsEngine();
  83905. if (!this._physicsEngine) {
  83906. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83907. }
  83908. }
  83909. /**
  83910. * @param {Vector3} origin the origin of the explosion
  83911. * @param {number} radius the explosion radius
  83912. * @param {number} strength the explosion strength
  83913. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83914. */
  83915. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83916. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83917. if (!this._physicsEngine) {
  83918. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83919. return null;
  83920. }
  83921. var impostors = this._physicsEngine.getImpostors();
  83922. if (impostors.length === 0) {
  83923. return null;
  83924. }
  83925. var event = new PhysicsRadialExplosionEvent(this._scene);
  83926. impostors.forEach(function (impostor) {
  83927. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83928. if (!impostorForceAndContactPoint) {
  83929. return;
  83930. }
  83931. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83932. });
  83933. event.dispose(false);
  83934. return event;
  83935. };
  83936. /**
  83937. * @param {Vector3} origin the origin of the explosion
  83938. * @param {number} radius the explosion radius
  83939. * @param {number} strength the explosion strength
  83940. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83941. */
  83942. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83943. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83944. if (!this._physicsEngine) {
  83945. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83946. return null;
  83947. }
  83948. var impostors = this._physicsEngine.getImpostors();
  83949. if (impostors.length === 0) {
  83950. return null;
  83951. }
  83952. var event = new PhysicsRadialExplosionEvent(this._scene);
  83953. impostors.forEach(function (impostor) {
  83954. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83955. if (!impostorForceAndContactPoint) {
  83956. return;
  83957. }
  83958. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83959. });
  83960. event.dispose(false);
  83961. return event;
  83962. };
  83963. /**
  83964. * @param {Vector3} origin the origin of the explosion
  83965. * @param {number} radius the explosion radius
  83966. * @param {number} strength the explosion strength
  83967. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83968. */
  83969. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83970. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83971. if (!this._physicsEngine) {
  83972. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83973. return null;
  83974. }
  83975. var impostors = this._physicsEngine.getImpostors();
  83976. if (impostors.length === 0) {
  83977. return null;
  83978. }
  83979. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83980. event.dispose(false);
  83981. return event;
  83982. };
  83983. /**
  83984. * @param {Vector3} origin the origin of the updraft
  83985. * @param {number} radius the radius of the updraft
  83986. * @param {number} strength the strength of the updraft
  83987. * @param {number} height the height of the updraft
  83988. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83989. */
  83990. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83991. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83992. if (!this._physicsEngine) {
  83993. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83994. return null;
  83995. }
  83996. if (this._physicsEngine.getImpostors().length === 0) {
  83997. return null;
  83998. }
  83999. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84000. event.dispose(false);
  84001. return event;
  84002. };
  84003. /**
  84004. * @param {Vector3} origin the of the vortex
  84005. * @param {number} radius the radius of the vortex
  84006. * @param {number} strength the strength of the vortex
  84007. * @param {number} height the height of the vortex
  84008. */
  84009. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84010. if (!this._physicsEngine) {
  84011. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84012. return null;
  84013. }
  84014. if (this._physicsEngine.getImpostors().length === 0) {
  84015. return null;
  84016. }
  84017. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84018. event.dispose(false);
  84019. return event;
  84020. };
  84021. return PhysicsHelper;
  84022. }());
  84023. BABYLON.PhysicsHelper = PhysicsHelper;
  84024. /***** Radial explosion *****/
  84025. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84026. function PhysicsRadialExplosionEvent(scene) {
  84027. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84028. this._rays = [];
  84029. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84030. this._scene = scene;
  84031. }
  84032. /**
  84033. * Returns the data related to the radial explosion event (sphere & rays).
  84034. * @returns {PhysicsRadialExplosionEventData}
  84035. */
  84036. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84037. this._dataFetched = true;
  84038. return {
  84039. sphere: this._sphere,
  84040. rays: this._rays,
  84041. };
  84042. };
  84043. /**
  84044. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84045. * @param impostor
  84046. * @param {Vector3} origin the origin of the explosion
  84047. * @param {number} radius the explosion radius
  84048. * @param {number} strength the explosion strength
  84049. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84050. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84051. */
  84052. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84053. if (impostor.mass === 0) {
  84054. return null;
  84055. }
  84056. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84057. return null;
  84058. }
  84059. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84060. return null;
  84061. }
  84062. var impostorObjectCenter = impostor.getObjectCenter();
  84063. var direction = impostorObjectCenter.subtract(origin);
  84064. var ray = new BABYLON.Ray(origin, direction, radius);
  84065. this._rays.push(ray);
  84066. var hit = ray.intersectsMesh(impostor.object);
  84067. var contactPoint = hit.pickedPoint;
  84068. if (!contactPoint) {
  84069. return null;
  84070. }
  84071. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84072. if (distanceFromOrigin > radius) {
  84073. return null;
  84074. }
  84075. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84076. ? strength
  84077. : strength * (1 - (distanceFromOrigin / radius));
  84078. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84079. return { force: force, contactPoint: contactPoint };
  84080. };
  84081. /**
  84082. * Disposes the sphere.
  84083. * @param {bolean} force
  84084. */
  84085. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84086. var _this = this;
  84087. if (force === void 0) { force = true; }
  84088. if (force) {
  84089. this._sphere.dispose();
  84090. }
  84091. else {
  84092. setTimeout(function () {
  84093. if (!_this._dataFetched) {
  84094. _this._sphere.dispose();
  84095. }
  84096. }, 0);
  84097. }
  84098. };
  84099. /*** Helpers ***/
  84100. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84101. if (!this._sphere) {
  84102. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84103. this._sphere.isVisible = false;
  84104. }
  84105. };
  84106. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84107. var impostorObject = impostor.object;
  84108. this._prepareSphere();
  84109. this._sphere.position = origin;
  84110. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84111. this._sphere._updateBoundingInfo();
  84112. this._sphere.computeWorldMatrix(true);
  84113. return this._sphere.intersectsMesh(impostorObject, true);
  84114. };
  84115. return PhysicsRadialExplosionEvent;
  84116. }());
  84117. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84118. /***** Gravitational Field *****/
  84119. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84120. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84121. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84122. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84123. this._physicsHelper = physicsHelper;
  84124. this._scene = scene;
  84125. this._origin = origin;
  84126. this._radius = radius;
  84127. this._strength = strength;
  84128. this._falloff = falloff;
  84129. this._tickCallback = this._tick.bind(this);
  84130. }
  84131. /**
  84132. * Returns the data related to the gravitational field event (sphere).
  84133. * @returns {PhysicsGravitationalFieldEventData}
  84134. */
  84135. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84136. this._dataFetched = true;
  84137. return {
  84138. sphere: this._sphere,
  84139. };
  84140. };
  84141. /**
  84142. * Enables the gravitational field.
  84143. */
  84144. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84145. this._tickCallback.call(this);
  84146. this._scene.registerBeforeRender(this._tickCallback);
  84147. };
  84148. /**
  84149. * Disables the gravitational field.
  84150. */
  84151. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84152. this._scene.unregisterBeforeRender(this._tickCallback);
  84153. };
  84154. /**
  84155. * Disposes the sphere.
  84156. * @param {bolean} force
  84157. */
  84158. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84159. var _this = this;
  84160. if (force === void 0) { force = true; }
  84161. if (force) {
  84162. this._sphere.dispose();
  84163. }
  84164. else {
  84165. setTimeout(function () {
  84166. if (!_this._dataFetched) {
  84167. _this._sphere.dispose();
  84168. }
  84169. }, 0);
  84170. }
  84171. };
  84172. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84173. // Since the params won't change, we fetch the event only once
  84174. if (this._sphere) {
  84175. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84176. }
  84177. else {
  84178. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84179. if (radialExplosionEvent) {
  84180. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84181. }
  84182. }
  84183. };
  84184. return PhysicsGravitationalFieldEvent;
  84185. }());
  84186. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84187. /***** Updraft *****/
  84188. var PhysicsUpdraftEvent = /** @class */ (function () {
  84189. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84190. this._scene = _scene;
  84191. this._origin = _origin;
  84192. this._radius = _radius;
  84193. this._strength = _strength;
  84194. this._height = _height;
  84195. this._updraftMode = _updraftMode;
  84196. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84197. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84198. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84199. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84200. this._physicsEngine = this._scene.getPhysicsEngine();
  84201. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84202. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84203. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84204. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84205. }
  84206. this._tickCallback = this._tick.bind(this);
  84207. }
  84208. /**
  84209. * Returns the data related to the updraft event (cylinder).
  84210. * @returns {PhysicsUpdraftEventData}
  84211. */
  84212. PhysicsUpdraftEvent.prototype.getData = function () {
  84213. this._dataFetched = true;
  84214. return {
  84215. cylinder: this._cylinder,
  84216. };
  84217. };
  84218. /**
  84219. * Enables the updraft.
  84220. */
  84221. PhysicsUpdraftEvent.prototype.enable = function () {
  84222. this._tickCallback.call(this);
  84223. this._scene.registerBeforeRender(this._tickCallback);
  84224. };
  84225. /**
  84226. * Disables the cortex.
  84227. */
  84228. PhysicsUpdraftEvent.prototype.disable = function () {
  84229. this._scene.unregisterBeforeRender(this._tickCallback);
  84230. };
  84231. /**
  84232. * Disposes the sphere.
  84233. * @param {bolean} force
  84234. */
  84235. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84236. var _this = this;
  84237. if (force === void 0) { force = true; }
  84238. if (force) {
  84239. this._cylinder.dispose();
  84240. }
  84241. else {
  84242. setTimeout(function () {
  84243. if (!_this._dataFetched) {
  84244. _this._cylinder.dispose();
  84245. }
  84246. }, 0);
  84247. }
  84248. };
  84249. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84250. if (impostor.mass === 0) {
  84251. return null;
  84252. }
  84253. if (!this._intersectsWithCylinder(impostor)) {
  84254. return null;
  84255. }
  84256. var impostorObjectCenter = impostor.getObjectCenter();
  84257. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84258. var direction = this._originDirection;
  84259. }
  84260. else {
  84261. var direction = impostorObjectCenter.subtract(this._originTop);
  84262. }
  84263. var multiplier = this._strength * -1;
  84264. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84265. return { force: force, contactPoint: impostorObjectCenter };
  84266. };
  84267. PhysicsUpdraftEvent.prototype._tick = function () {
  84268. var _this = this;
  84269. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84270. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84271. if (!impostorForceAndContactPoint) {
  84272. return;
  84273. }
  84274. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84275. });
  84276. };
  84277. /*** Helpers ***/
  84278. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84279. if (!this._cylinder) {
  84280. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84281. height: this._height,
  84282. diameter: this._radius * 2,
  84283. }, this._scene);
  84284. this._cylinder.isVisible = false;
  84285. }
  84286. };
  84287. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84288. var impostorObject = impostor.object;
  84289. this._prepareCylinder();
  84290. this._cylinder.position = this._cylinderPosition;
  84291. return this._cylinder.intersectsMesh(impostorObject, true);
  84292. };
  84293. return PhysicsUpdraftEvent;
  84294. }());
  84295. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84296. /***** Vortex *****/
  84297. var PhysicsVortexEvent = /** @class */ (function () {
  84298. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84299. this._scene = _scene;
  84300. this._origin = _origin;
  84301. this._radius = _radius;
  84302. this._strength = _strength;
  84303. this._height = _height;
  84304. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84305. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84306. this._updraftMultiplier = 0.02;
  84307. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84308. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84309. this._physicsEngine = this._scene.getPhysicsEngine();
  84310. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84311. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84312. this._tickCallback = this._tick.bind(this);
  84313. }
  84314. /**
  84315. * Returns the data related to the vortex event (cylinder).
  84316. * @returns {PhysicsVortexEventData}
  84317. */
  84318. PhysicsVortexEvent.prototype.getData = function () {
  84319. this._dataFetched = true;
  84320. return {
  84321. cylinder: this._cylinder,
  84322. };
  84323. };
  84324. /**
  84325. * Enables the vortex.
  84326. */
  84327. PhysicsVortexEvent.prototype.enable = function () {
  84328. this._tickCallback.call(this);
  84329. this._scene.registerBeforeRender(this._tickCallback);
  84330. };
  84331. /**
  84332. * Disables the cortex.
  84333. */
  84334. PhysicsVortexEvent.prototype.disable = function () {
  84335. this._scene.unregisterBeforeRender(this._tickCallback);
  84336. };
  84337. /**
  84338. * Disposes the sphere.
  84339. * @param {bolean} force
  84340. */
  84341. PhysicsVortexEvent.prototype.dispose = function (force) {
  84342. var _this = this;
  84343. if (force === void 0) { force = true; }
  84344. if (force) {
  84345. this._cylinder.dispose();
  84346. }
  84347. else {
  84348. setTimeout(function () {
  84349. if (!_this._dataFetched) {
  84350. _this._cylinder.dispose();
  84351. }
  84352. }, 0);
  84353. }
  84354. };
  84355. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84356. if (impostor.mass === 0) {
  84357. return null;
  84358. }
  84359. if (!this._intersectsWithCylinder(impostor)) {
  84360. return null;
  84361. }
  84362. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84363. return null;
  84364. }
  84365. var impostorObjectCenter = impostor.getObjectCenter();
  84366. 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)
  84367. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84368. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84369. var hit = ray.intersectsMesh(impostor.object);
  84370. var contactPoint = hit.pickedPoint;
  84371. if (!contactPoint) {
  84372. return null;
  84373. }
  84374. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84375. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84376. var directionToOrigin = contactPoint.normalize();
  84377. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84378. directionToOrigin = directionToOrigin.negate();
  84379. }
  84380. // TODO: find a more physically based solution
  84381. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84382. var forceX = directionToOrigin.x * this._strength / 8;
  84383. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84384. var forceZ = directionToOrigin.z * this._strength / 8;
  84385. }
  84386. else {
  84387. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84388. var forceY = this._originTop.y * this._updraftMultiplier;
  84389. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84390. }
  84391. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84392. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84393. return { force: force, contactPoint: impostorObjectCenter };
  84394. };
  84395. PhysicsVortexEvent.prototype._tick = function () {
  84396. var _this = this;
  84397. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84398. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84399. if (!impostorForceAndContactPoint) {
  84400. return;
  84401. }
  84402. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84403. });
  84404. };
  84405. /*** Helpers ***/
  84406. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84407. if (!this._cylinder) {
  84408. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84409. height: this._height,
  84410. diameter: this._radius * 2,
  84411. }, this._scene);
  84412. this._cylinder.isVisible = false;
  84413. }
  84414. };
  84415. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84416. var impostorObject = impostor.object;
  84417. this._prepareCylinder();
  84418. this._cylinder.position = this._cylinderPosition;
  84419. return this._cylinder.intersectsMesh(impostorObject, true);
  84420. };
  84421. return PhysicsVortexEvent;
  84422. }());
  84423. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84424. /***** Enums *****/
  84425. /**
  84426. * The strenght of the force in correspondence to the distance of the affected object
  84427. */
  84428. var PhysicsRadialImpulseFalloff;
  84429. (function (PhysicsRadialImpulseFalloff) {
  84430. /** Defines that impulse is constant in strength across it's whole radius */
  84431. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84432. /** DEfines that impulse gets weaker if it's further from the origin */
  84433. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84434. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84435. /**
  84436. * The strenght of the force in correspondence to the distance of the affected object
  84437. */
  84438. var PhysicsUpdraftMode;
  84439. (function (PhysicsUpdraftMode) {
  84440. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84441. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84442. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84443. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84444. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84445. })(BABYLON || (BABYLON = {}));
  84446. //# sourceMappingURL=babylon.physicsHelper.js.map
  84447. var BABYLON;
  84448. (function (BABYLON) {
  84449. var CannonJSPlugin = /** @class */ (function () {
  84450. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84451. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84452. if (iterations === void 0) { iterations = 10; }
  84453. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84454. this.name = "CannonJSPlugin";
  84455. this._physicsMaterials = new Array();
  84456. this._fixedTimeStep = 1 / 60;
  84457. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84458. this.BJSCANNON = CANNON;
  84459. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84460. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84461. this._tmpPosition = BABYLON.Vector3.Zero();
  84462. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84463. this._tmpUnityRotation = new BABYLON.Quaternion();
  84464. if (!this.isSupported()) {
  84465. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84466. return;
  84467. }
  84468. this._extendNamespace();
  84469. this.world = new this.BJSCANNON.World();
  84470. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  84471. this.world.solver.iterations = iterations;
  84472. }
  84473. CannonJSPlugin.prototype.setGravity = function (gravity) {
  84474. this.world.gravity.copy(gravity);
  84475. };
  84476. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  84477. this._fixedTimeStep = timeStep;
  84478. };
  84479. CannonJSPlugin.prototype.getTimeStep = function () {
  84480. return this._fixedTimeStep;
  84481. };
  84482. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  84483. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  84484. };
  84485. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84486. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84487. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84488. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  84489. };
  84490. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84491. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84492. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84493. impostor.physicsBody.applyForce(impulse, worldPoint);
  84494. };
  84495. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84496. //parent-child relationship. Does this impostor has a parent impostor?
  84497. if (impostor.parent) {
  84498. if (impostor.physicsBody) {
  84499. this.removePhysicsBody(impostor);
  84500. //TODO is that needed?
  84501. impostor.forceUpdate();
  84502. }
  84503. return;
  84504. }
  84505. //should a new body be created for this impostor?
  84506. if (impostor.isBodyInitRequired()) {
  84507. var shape = this._createShape(impostor);
  84508. //unregister events, if body is being changed
  84509. var oldBody = impostor.physicsBody;
  84510. if (oldBody) {
  84511. this.removePhysicsBody(impostor);
  84512. }
  84513. //create the body and material
  84514. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  84515. var bodyCreationObject = {
  84516. mass: impostor.getParam("mass"),
  84517. material: material
  84518. };
  84519. // A simple extend, in case native options were used.
  84520. var nativeOptions = impostor.getParam("nativeOptions");
  84521. for (var key in nativeOptions) {
  84522. if (nativeOptions.hasOwnProperty(key)) {
  84523. bodyCreationObject[key] = nativeOptions[key];
  84524. }
  84525. }
  84526. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  84527. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  84528. this.world.addEventListener("preStep", impostor.beforeStep);
  84529. this.world.addEventListener("postStep", impostor.afterStep);
  84530. impostor.physicsBody.addShape(shape);
  84531. this.world.add(impostor.physicsBody);
  84532. //try to keep the body moving in the right direction by taking old properties.
  84533. //Should be tested!
  84534. if (oldBody) {
  84535. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84536. impostor.physicsBody[param].copy(oldBody[param]);
  84537. });
  84538. }
  84539. this._processChildMeshes(impostor);
  84540. }
  84541. //now update the body's transformation
  84542. this._updatePhysicsBodyTransformation(impostor);
  84543. };
  84544. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  84545. var _this = this;
  84546. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  84547. var currentRotation = mainImpostor.object.rotationQuaternion;
  84548. if (meshChildren.length) {
  84549. var processMesh = function (localPosition, mesh) {
  84550. if (!currentRotation || !mesh.rotationQuaternion) {
  84551. return;
  84552. }
  84553. var childImpostor = mesh.getPhysicsImpostor();
  84554. if (childImpostor) {
  84555. var parent = childImpostor.parent;
  84556. if (parent !== mainImpostor) {
  84557. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  84558. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  84559. if (childImpostor.physicsBody) {
  84560. _this.removePhysicsBody(childImpostor);
  84561. childImpostor.physicsBody = null;
  84562. }
  84563. childImpostor.parent = mainImpostor;
  84564. childImpostor.resetUpdateFlags();
  84565. 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));
  84566. //Add the mass of the children.
  84567. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  84568. }
  84569. }
  84570. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  84571. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  84572. };
  84573. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  84574. }
  84575. };
  84576. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84577. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  84578. this.world.removeEventListener("preStep", impostor.beforeStep);
  84579. this.world.removeEventListener("postStep", impostor.afterStep);
  84580. this.world.remove(impostor.physicsBody);
  84581. };
  84582. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84583. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84584. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84585. if (!mainBody || !connectedBody) {
  84586. return;
  84587. }
  84588. var constraint;
  84589. var jointData = impostorJoint.joint.jointData;
  84590. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  84591. var constraintData = {
  84592. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  84593. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  84594. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  84595. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  84596. maxForce: jointData.nativeParams.maxForce,
  84597. collideConnected: !!jointData.collision
  84598. };
  84599. switch (impostorJoint.joint.type) {
  84600. case BABYLON.PhysicsJoint.HingeJoint:
  84601. case BABYLON.PhysicsJoint.Hinge2Joint:
  84602. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  84603. break;
  84604. case BABYLON.PhysicsJoint.DistanceJoint:
  84605. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  84606. break;
  84607. case BABYLON.PhysicsJoint.SpringJoint:
  84608. var springData = jointData;
  84609. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  84610. restLength: springData.length,
  84611. stiffness: springData.stiffness,
  84612. damping: springData.damping,
  84613. localAnchorA: constraintData.pivotA,
  84614. localAnchorB: constraintData.pivotB
  84615. });
  84616. break;
  84617. case BABYLON.PhysicsJoint.LockJoint:
  84618. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  84619. break;
  84620. case BABYLON.PhysicsJoint.PointToPointJoint:
  84621. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84622. default:
  84623. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  84624. break;
  84625. }
  84626. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  84627. constraint.collideConnected = !!jointData.collision;
  84628. impostorJoint.joint.physicsJoint = constraint;
  84629. //don't add spring as constraint, as it is not one.
  84630. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  84631. this.world.addConstraint(constraint);
  84632. }
  84633. else {
  84634. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  84635. constraint.applyForce();
  84636. });
  84637. }
  84638. };
  84639. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84640. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  84641. };
  84642. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  84643. var index;
  84644. var mat;
  84645. for (index = 0; index < this._physicsMaterials.length; index++) {
  84646. mat = this._physicsMaterials[index];
  84647. if (mat.friction === friction && mat.restitution === restitution) {
  84648. return mat;
  84649. }
  84650. }
  84651. var currentMat = new this.BJSCANNON.Material(name);
  84652. currentMat.friction = friction;
  84653. currentMat.restitution = restitution;
  84654. this._physicsMaterials.push(currentMat);
  84655. return currentMat;
  84656. };
  84657. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  84658. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  84659. };
  84660. CannonJSPlugin.prototype._createShape = function (impostor) {
  84661. var object = impostor.object;
  84662. var returnValue;
  84663. var extendSize = impostor.getObjectExtendSize();
  84664. switch (impostor.type) {
  84665. case BABYLON.PhysicsImpostor.SphereImpostor:
  84666. var radiusX = extendSize.x;
  84667. var radiusY = extendSize.y;
  84668. var radiusZ = extendSize.z;
  84669. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  84670. break;
  84671. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  84672. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84673. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  84674. break;
  84675. case BABYLON.PhysicsImpostor.BoxImpostor:
  84676. var box = extendSize.scale(0.5);
  84677. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  84678. break;
  84679. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84680. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  84681. returnValue = new this.BJSCANNON.Plane();
  84682. break;
  84683. case BABYLON.PhysicsImpostor.MeshImpostor:
  84684. // should transform the vertex data to world coordinates!!
  84685. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  84686. var rawFaces = object.getIndices ? object.getIndices() : [];
  84687. if (!rawVerts)
  84688. return;
  84689. // get only scale! so the object could transform correctly.
  84690. var oldPosition = object.position.clone();
  84691. var oldRotation = object.rotation && object.rotation.clone();
  84692. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  84693. object.position.copyFromFloats(0, 0, 0);
  84694. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84695. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84696. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84697. var transform = object.computeWorldMatrix(true);
  84698. // convert rawVerts to object space
  84699. var temp = new Array();
  84700. var index;
  84701. for (index = 0; index < rawVerts.length; index += 3) {
  84702. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  84703. }
  84704. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  84705. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  84706. //now set back the transformation!
  84707. object.position.copyFrom(oldPosition);
  84708. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  84709. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  84710. break;
  84711. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  84712. var oldPosition2 = object.position.clone();
  84713. var oldRotation2 = object.rotation && object.rotation.clone();
  84714. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  84715. object.position.copyFromFloats(0, 0, 0);
  84716. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84717. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84718. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84719. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  84720. returnValue = this._createHeightmap(object);
  84721. object.position.copyFrom(oldPosition2);
  84722. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  84723. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  84724. object.computeWorldMatrix(true);
  84725. break;
  84726. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84727. returnValue = new this.BJSCANNON.Particle();
  84728. break;
  84729. }
  84730. return returnValue;
  84731. };
  84732. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  84733. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84734. var transform = object.computeWorldMatrix(true);
  84735. // convert rawVerts to object space
  84736. var temp = new Array();
  84737. var index;
  84738. for (index = 0; index < pos.length; index += 3) {
  84739. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  84740. }
  84741. pos = temp;
  84742. var matrix = new Array();
  84743. //For now pointDepth will not be used and will be automatically calculated.
  84744. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  84745. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  84746. var boundingInfo = object.getBoundingInfo();
  84747. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  84748. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  84749. var elementSize = dim * 2 / arraySize;
  84750. for (var i = 0; i < pos.length; i = i + 3) {
  84751. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  84752. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  84753. var y = -pos[i + 2] + minY;
  84754. if (!matrix[x]) {
  84755. matrix[x] = [];
  84756. }
  84757. if (!matrix[x][z]) {
  84758. matrix[x][z] = y;
  84759. }
  84760. matrix[x][z] = Math.max(y, matrix[x][z]);
  84761. }
  84762. for (var x = 0; x <= arraySize; ++x) {
  84763. if (!matrix[x]) {
  84764. var loc = 1;
  84765. while (!matrix[(x + loc) % arraySize]) {
  84766. loc++;
  84767. }
  84768. matrix[x] = matrix[(x + loc) % arraySize].slice();
  84769. //console.log("missing x", x);
  84770. }
  84771. for (var z = 0; z <= arraySize; ++z) {
  84772. if (!matrix[x][z]) {
  84773. var loc = 1;
  84774. var newValue;
  84775. while (newValue === undefined) {
  84776. newValue = matrix[x][(z + loc++) % arraySize];
  84777. }
  84778. matrix[x][z] = newValue;
  84779. }
  84780. }
  84781. }
  84782. var shape = new this.BJSCANNON.Heightfield(matrix, {
  84783. elementSize: elementSize
  84784. });
  84785. //For future reference, needed for body transformation
  84786. shape.minY = minY;
  84787. return shape;
  84788. };
  84789. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  84790. var object = impostor.object;
  84791. //make sure it is updated...
  84792. object.computeWorldMatrix && object.computeWorldMatrix(true);
  84793. // The delta between the mesh position and the mesh bounding box center
  84794. var bInfo = object.getBoundingInfo();
  84795. if (!bInfo)
  84796. return;
  84797. var center = impostor.getObjectCenter();
  84798. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84799. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84800. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84801. this._tmpPosition.copyFrom(center);
  84802. var quaternion = object.rotationQuaternion;
  84803. if (!quaternion) {
  84804. return;
  84805. }
  84806. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84807. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84808. //-90 DEG in X, precalculated
  84809. quaternion = quaternion.multiply(this._minus90X);
  84810. //Invert! (Precalculated, 90 deg in X)
  84811. //No need to clone. this will never change.
  84812. impostor.setDeltaRotation(this._plus90X);
  84813. }
  84814. //If it is a heightfield, if should be centered.
  84815. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84816. var mesh = object;
  84817. var boundingInfo = mesh.getBoundingInfo();
  84818. //calculate the correct body position:
  84819. var rotationQuaternion = mesh.rotationQuaternion;
  84820. mesh.rotationQuaternion = this._tmpUnityRotation;
  84821. mesh.computeWorldMatrix(true);
  84822. //get original center with no rotation
  84823. var c = center.clone();
  84824. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84825. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84826. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84827. mesh.setPreTransformMatrix(p);
  84828. mesh.computeWorldMatrix(true);
  84829. //calculate the translation
  84830. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84831. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84832. //add it inverted to the delta
  84833. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84834. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84835. //rotation is back
  84836. mesh.rotationQuaternion = rotationQuaternion;
  84837. mesh.setPreTransformMatrix(oldPivot);
  84838. mesh.computeWorldMatrix(true);
  84839. }
  84840. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84841. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84842. //this._tmpPosition.copyFrom(object.position);
  84843. }
  84844. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84845. //Now update the impostor object
  84846. impostor.physicsBody.position.copy(this._tmpPosition);
  84847. impostor.physicsBody.quaternion.copy(quaternion);
  84848. };
  84849. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84850. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84851. if (impostor.object.rotationQuaternion) {
  84852. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84853. }
  84854. };
  84855. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84856. impostor.physicsBody.position.copy(newPosition);
  84857. impostor.physicsBody.quaternion.copy(newRotation);
  84858. };
  84859. CannonJSPlugin.prototype.isSupported = function () {
  84860. return this.BJSCANNON !== undefined;
  84861. };
  84862. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84863. impostor.physicsBody.velocity.copy(velocity);
  84864. };
  84865. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84866. impostor.physicsBody.angularVelocity.copy(velocity);
  84867. };
  84868. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84869. var v = impostor.physicsBody.velocity;
  84870. if (!v) {
  84871. return null;
  84872. }
  84873. return new BABYLON.Vector3(v.x, v.y, v.z);
  84874. };
  84875. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84876. var v = impostor.physicsBody.angularVelocity;
  84877. if (!v) {
  84878. return null;
  84879. }
  84880. return new BABYLON.Vector3(v.x, v.y, v.z);
  84881. };
  84882. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84883. impostor.physicsBody.mass = mass;
  84884. impostor.physicsBody.updateMassProperties();
  84885. };
  84886. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84887. return impostor.physicsBody.mass;
  84888. };
  84889. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84890. return impostor.physicsBody.material.friction;
  84891. };
  84892. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84893. impostor.physicsBody.material.friction = friction;
  84894. };
  84895. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84896. return impostor.physicsBody.material.restitution;
  84897. };
  84898. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84899. impostor.physicsBody.material.restitution = restitution;
  84900. };
  84901. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84902. impostor.physicsBody.sleep();
  84903. };
  84904. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84905. impostor.physicsBody.wakeUp();
  84906. };
  84907. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84908. joint.physicsJoint.distance = maxDistance;
  84909. };
  84910. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84911. // if (!motorIndex) {
  84912. // joint.physicsJoint.enableMotor();
  84913. // }
  84914. // }
  84915. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84916. // if (!motorIndex) {
  84917. // joint.physicsJoint.disableMotor();
  84918. // }
  84919. // }
  84920. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84921. if (!motorIndex) {
  84922. joint.physicsJoint.enableMotor();
  84923. joint.physicsJoint.setMotorSpeed(speed);
  84924. if (maxForce) {
  84925. this.setLimit(joint, maxForce);
  84926. }
  84927. }
  84928. };
  84929. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84930. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84931. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84932. };
  84933. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84934. var body = impostor.physicsBody;
  84935. mesh.position.x = body.position.x;
  84936. mesh.position.y = body.position.y;
  84937. mesh.position.z = body.position.z;
  84938. if (mesh.rotationQuaternion) {
  84939. mesh.rotationQuaternion.x = body.quaternion.x;
  84940. mesh.rotationQuaternion.y = body.quaternion.y;
  84941. mesh.rotationQuaternion.z = body.quaternion.z;
  84942. mesh.rotationQuaternion.w = body.quaternion.w;
  84943. }
  84944. };
  84945. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84946. var shape = impostor.physicsBody.shapes[0];
  84947. return shape.boundingSphereRadius;
  84948. };
  84949. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84950. var shape = impostor.physicsBody.shapes[0];
  84951. result.x = shape.halfExtents.x * 2;
  84952. result.y = shape.halfExtents.y * 2;
  84953. result.z = shape.halfExtents.z * 2;
  84954. };
  84955. CannonJSPlugin.prototype.dispose = function () {
  84956. };
  84957. CannonJSPlugin.prototype._extendNamespace = function () {
  84958. //this will force cannon to execute at least one step when using interpolation
  84959. var step_tmp1 = new this.BJSCANNON.Vec3();
  84960. var Engine = this.BJSCANNON;
  84961. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84962. maxSubSteps = maxSubSteps || 10;
  84963. timeSinceLastCalled = timeSinceLastCalled || 0;
  84964. if (timeSinceLastCalled === 0) {
  84965. this.internalStep(dt);
  84966. this.time += dt;
  84967. }
  84968. else {
  84969. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84970. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84971. var t0 = performance.now();
  84972. for (var i = 0; i !== internalSteps; i++) {
  84973. this.internalStep(dt);
  84974. if (performance.now() - t0 > dt * 1000) {
  84975. break;
  84976. }
  84977. }
  84978. this.time += timeSinceLastCalled;
  84979. var h = this.time % dt;
  84980. var h_div_dt = h / dt;
  84981. var interpvelo = step_tmp1;
  84982. var bodies = this.bodies;
  84983. for (var j = 0; j !== bodies.length; j++) {
  84984. var b = bodies[j];
  84985. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84986. b.position.vsub(b.previousPosition, interpvelo);
  84987. interpvelo.scale(h_div_dt, interpvelo);
  84988. b.position.vadd(interpvelo, b.interpolatedPosition);
  84989. }
  84990. else {
  84991. b.interpolatedPosition.copy(b.position);
  84992. b.interpolatedQuaternion.copy(b.quaternion);
  84993. }
  84994. }
  84995. }
  84996. };
  84997. };
  84998. return CannonJSPlugin;
  84999. }());
  85000. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85001. })(BABYLON || (BABYLON = {}));
  85002. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85003. var BABYLON;
  85004. (function (BABYLON) {
  85005. var OimoJSPlugin = /** @class */ (function () {
  85006. function OimoJSPlugin(iterations) {
  85007. this.name = "OimoJSPlugin";
  85008. this._tmpImpostorsArray = [];
  85009. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85010. this.BJSOIMO = OIMO;
  85011. this.world = new this.BJSOIMO.World({
  85012. iterations: iterations
  85013. });
  85014. this.world.clear();
  85015. }
  85016. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85017. this.world.gravity.copy(gravity);
  85018. };
  85019. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85020. this.world.timeStep = timeStep;
  85021. };
  85022. OimoJSPlugin.prototype.getTimeStep = function () {
  85023. return this.world.timeStep;
  85024. };
  85025. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85026. var _this = this;
  85027. impostors.forEach(function (impostor) {
  85028. impostor.beforeStep();
  85029. });
  85030. this.world.step();
  85031. impostors.forEach(function (impostor) {
  85032. impostor.afterStep();
  85033. //update the ordered impostors array
  85034. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85035. });
  85036. //check for collisions
  85037. var contact = this.world.contacts;
  85038. while (contact !== null) {
  85039. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85040. contact = contact.next;
  85041. continue;
  85042. }
  85043. //is this body colliding with any other? get the impostor
  85044. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85045. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85046. if (!mainImpostor || !collidingImpostor) {
  85047. contact = contact.next;
  85048. continue;
  85049. }
  85050. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85051. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85052. contact = contact.next;
  85053. }
  85054. };
  85055. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85056. var mass = impostor.physicsBody.mass;
  85057. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85058. };
  85059. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85060. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85061. this.applyImpulse(impostor, force, contactPoint);
  85062. };
  85063. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85064. var _this = this;
  85065. //parent-child relationship. Does this impostor has a parent impostor?
  85066. if (impostor.parent) {
  85067. if (impostor.physicsBody) {
  85068. this.removePhysicsBody(impostor);
  85069. //TODO is that needed?
  85070. impostor.forceUpdate();
  85071. }
  85072. return;
  85073. }
  85074. if (impostor.isBodyInitRequired()) {
  85075. var bodyConfig = {
  85076. name: impostor.uniqueId,
  85077. //Oimo must have mass, also for static objects.
  85078. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85079. size: [],
  85080. type: [],
  85081. pos: [],
  85082. posShape: [],
  85083. rot: [],
  85084. rotShape: [],
  85085. move: impostor.getParam("mass") !== 0,
  85086. density: impostor.getParam("mass"),
  85087. friction: impostor.getParam("friction"),
  85088. restitution: impostor.getParam("restitution"),
  85089. //Supporting older versions of Oimo
  85090. world: this.world
  85091. };
  85092. var impostors = [impostor];
  85093. var addToArray = function (parent) {
  85094. if (!parent.getChildMeshes)
  85095. return;
  85096. parent.getChildMeshes().forEach(function (m) {
  85097. if (m.physicsImpostor) {
  85098. impostors.push(m.physicsImpostor);
  85099. //m.physicsImpostor._init();
  85100. }
  85101. });
  85102. };
  85103. addToArray(impostor.object);
  85104. var checkWithEpsilon_1 = function (value) {
  85105. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85106. };
  85107. impostors.forEach(function (i) {
  85108. if (!i.object.rotationQuaternion) {
  85109. return;
  85110. }
  85111. //get the correct bounding box
  85112. var oldQuaternion = i.object.rotationQuaternion;
  85113. var rot = oldQuaternion.toEulerAngles();
  85114. var extendSize = i.getObjectExtendSize();
  85115. var radToDeg = 57.295779513082320876;
  85116. if (i === impostor) {
  85117. var center = impostor.getObjectCenter();
  85118. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85119. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85120. //Can also use Array.prototype.push.apply
  85121. bodyConfig.pos.push(center.x);
  85122. bodyConfig.pos.push(center.y);
  85123. bodyConfig.pos.push(center.z);
  85124. bodyConfig.posShape.push(0, 0, 0);
  85125. //tmp solution
  85126. bodyConfig.rot.push(rot.x * radToDeg);
  85127. bodyConfig.rot.push(rot.y * radToDeg);
  85128. bodyConfig.rot.push(rot.z * radToDeg);
  85129. bodyConfig.rotShape.push(0, 0, 0);
  85130. }
  85131. else {
  85132. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85133. bodyConfig.posShape.push(localPosition.x);
  85134. bodyConfig.posShape.push(localPosition.y);
  85135. bodyConfig.posShape.push(localPosition.z);
  85136. bodyConfig.pos.push(0, 0, 0);
  85137. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85138. bodyConfig.rot.push(0);
  85139. bodyConfig.rot.push(0);
  85140. bodyConfig.rot.push(0);
  85141. bodyConfig.rotShape.push(rot.x * radToDeg);
  85142. bodyConfig.rotShape.push(rot.y * radToDeg);
  85143. bodyConfig.rotShape.push(rot.z * radToDeg);
  85144. }
  85145. // register mesh
  85146. switch (i.type) {
  85147. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85148. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85149. case BABYLON.PhysicsImpostor.SphereImpostor:
  85150. var radiusX = extendSize.x;
  85151. var radiusY = extendSize.y;
  85152. var radiusZ = extendSize.z;
  85153. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85154. bodyConfig.type.push('sphere');
  85155. //due to the way oimo works with compounds, add 3 times
  85156. bodyConfig.size.push(size);
  85157. bodyConfig.size.push(size);
  85158. bodyConfig.size.push(size);
  85159. break;
  85160. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85161. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85162. var sizeY = checkWithEpsilon_1(extendSize.y);
  85163. bodyConfig.type.push('cylinder');
  85164. bodyConfig.size.push(sizeX);
  85165. bodyConfig.size.push(sizeY);
  85166. //due to the way oimo works with compounds, add one more value.
  85167. bodyConfig.size.push(sizeY);
  85168. break;
  85169. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85170. case BABYLON.PhysicsImpostor.BoxImpostor:
  85171. default:
  85172. var sizeX = checkWithEpsilon_1(extendSize.x);
  85173. var sizeY = checkWithEpsilon_1(extendSize.y);
  85174. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85175. bodyConfig.type.push('box');
  85176. //if (i === impostor) {
  85177. bodyConfig.size.push(sizeX);
  85178. bodyConfig.size.push(sizeY);
  85179. bodyConfig.size.push(sizeZ);
  85180. //} else {
  85181. // bodyConfig.size.push(0,0,0);
  85182. //}
  85183. break;
  85184. }
  85185. //actually not needed, but hey...
  85186. i.object.rotationQuaternion = oldQuaternion;
  85187. });
  85188. impostor.physicsBody = this.world.add(bodyConfig);
  85189. }
  85190. else {
  85191. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85192. }
  85193. impostor.setDeltaPosition(this._tmpPositionVector);
  85194. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85195. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85196. };
  85197. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85198. //impostor.physicsBody.dispose();
  85199. //Same as : (older oimo versions)
  85200. this.world.removeRigidBody(impostor.physicsBody);
  85201. };
  85202. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85203. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85204. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85205. if (!mainBody || !connectedBody) {
  85206. return;
  85207. }
  85208. var jointData = impostorJoint.joint.jointData;
  85209. var options = jointData.nativeParams || {};
  85210. var type;
  85211. var nativeJointData = {
  85212. body1: mainBody,
  85213. body2: connectedBody,
  85214. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85215. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85216. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85217. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85218. min: options.min,
  85219. max: options.max,
  85220. collision: options.collision || jointData.collision,
  85221. spring: options.spring,
  85222. //supporting older version of Oimo
  85223. world: this.world
  85224. };
  85225. switch (impostorJoint.joint.type) {
  85226. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85227. type = "jointBall";
  85228. break;
  85229. case BABYLON.PhysicsJoint.SpringJoint:
  85230. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85231. var springData = jointData;
  85232. nativeJointData.min = springData.length || nativeJointData.min;
  85233. //Max should also be set, just make sure it is at least min
  85234. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85235. case BABYLON.PhysicsJoint.DistanceJoint:
  85236. type = "jointDistance";
  85237. nativeJointData.max = jointData.maxDistance;
  85238. break;
  85239. case BABYLON.PhysicsJoint.PrismaticJoint:
  85240. type = "jointPrisme";
  85241. break;
  85242. case BABYLON.PhysicsJoint.SliderJoint:
  85243. type = "jointSlide";
  85244. break;
  85245. case BABYLON.PhysicsJoint.WheelJoint:
  85246. type = "jointWheel";
  85247. break;
  85248. case BABYLON.PhysicsJoint.HingeJoint:
  85249. default:
  85250. type = "jointHinge";
  85251. break;
  85252. }
  85253. nativeJointData.type = type;
  85254. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85255. };
  85256. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85257. //Bug in Oimo prevents us from disposing a joint in the playground
  85258. //joint.joint.physicsJoint.dispose();
  85259. //So we will bruteforce it!
  85260. try {
  85261. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85262. }
  85263. catch (e) {
  85264. BABYLON.Tools.Warn(e);
  85265. }
  85266. };
  85267. OimoJSPlugin.prototype.isSupported = function () {
  85268. return this.BJSOIMO !== undefined;
  85269. };
  85270. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85271. if (!impostor.physicsBody.sleeping) {
  85272. //TODO check that
  85273. /*if (impostor.physicsBody.shapes.next) {
  85274. var parentShape = this._getLastShape(impostor.physicsBody);
  85275. impostor.object.position.copyFrom(parentShape.position);
  85276. console.log(parentShape.position);
  85277. } else {*/
  85278. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85279. //}
  85280. if (impostor.object.rotationQuaternion) {
  85281. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85282. }
  85283. }
  85284. };
  85285. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85286. var body = impostor.physicsBody;
  85287. body.position.copy(newPosition);
  85288. body.orientation.copy(newRotation);
  85289. body.syncShapes();
  85290. body.awake();
  85291. };
  85292. /*private _getLastShape(body: any): any {
  85293. var lastShape = body.shapes;
  85294. while (lastShape.next) {
  85295. lastShape = lastShape.next;
  85296. }
  85297. return lastShape;
  85298. }*/
  85299. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85300. impostor.physicsBody.linearVelocity.copy(velocity);
  85301. };
  85302. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85303. impostor.physicsBody.angularVelocity.copy(velocity);
  85304. };
  85305. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85306. var v = impostor.physicsBody.linearVelocity;
  85307. if (!v) {
  85308. return null;
  85309. }
  85310. return new BABYLON.Vector3(v.x, v.y, v.z);
  85311. };
  85312. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85313. var v = impostor.physicsBody.angularVelocity;
  85314. if (!v) {
  85315. return null;
  85316. }
  85317. return new BABYLON.Vector3(v.x, v.y, v.z);
  85318. };
  85319. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85320. var staticBody = mass === 0;
  85321. //this will actually set the body's density and not its mass.
  85322. //But this is how oimo treats the mass variable.
  85323. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85324. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85325. };
  85326. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85327. return impostor.physicsBody.shapes.density;
  85328. };
  85329. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85330. return impostor.physicsBody.shapes.friction;
  85331. };
  85332. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85333. impostor.physicsBody.shapes.friction = friction;
  85334. };
  85335. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85336. return impostor.physicsBody.shapes.restitution;
  85337. };
  85338. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85339. impostor.physicsBody.shapes.restitution = restitution;
  85340. };
  85341. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85342. impostor.physicsBody.sleep();
  85343. };
  85344. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85345. impostor.physicsBody.awake();
  85346. };
  85347. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85348. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85349. if (minDistance !== void 0) {
  85350. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85351. }
  85352. };
  85353. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85354. //TODO separate rotational and transational motors.
  85355. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85356. if (motor) {
  85357. motor.setMotor(speed, maxForce);
  85358. }
  85359. };
  85360. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85361. //TODO separate rotational and transational motors.
  85362. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85363. if (motor) {
  85364. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85365. }
  85366. };
  85367. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85368. var body = impostor.physicsBody;
  85369. mesh.position.x = body.position.x;
  85370. mesh.position.y = body.position.y;
  85371. mesh.position.z = body.position.z;
  85372. if (mesh.rotationQuaternion) {
  85373. mesh.rotationQuaternion.x = body.orientation.x;
  85374. mesh.rotationQuaternion.y = body.orientation.y;
  85375. mesh.rotationQuaternion.z = body.orientation.z;
  85376. mesh.rotationQuaternion.w = body.orientation.s;
  85377. }
  85378. };
  85379. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85380. return impostor.physicsBody.shapes.radius;
  85381. };
  85382. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85383. var shape = impostor.physicsBody.shapes;
  85384. result.x = shape.halfWidth * 2;
  85385. result.y = shape.halfHeight * 2;
  85386. result.z = shape.halfDepth * 2;
  85387. };
  85388. OimoJSPlugin.prototype.dispose = function () {
  85389. this.world.clear();
  85390. };
  85391. return OimoJSPlugin;
  85392. }());
  85393. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85394. })(BABYLON || (BABYLON = {}));
  85395. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85396. var BABYLON;
  85397. (function (BABYLON) {
  85398. /*
  85399. * Based on jsTGALoader - Javascript loader for TGA file
  85400. * By Vincent Thibault
  85401. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85402. */
  85403. var TGATools = /** @class */ (function () {
  85404. function TGATools() {
  85405. }
  85406. TGATools.GetTGAHeader = function (data) {
  85407. var offset = 0;
  85408. var header = {
  85409. id_length: data[offset++],
  85410. colormap_type: data[offset++],
  85411. image_type: data[offset++],
  85412. colormap_index: data[offset++] | data[offset++] << 8,
  85413. colormap_length: data[offset++] | data[offset++] << 8,
  85414. colormap_size: data[offset++],
  85415. origin: [
  85416. data[offset++] | data[offset++] << 8,
  85417. data[offset++] | data[offset++] << 8
  85418. ],
  85419. width: data[offset++] | data[offset++] << 8,
  85420. height: data[offset++] | data[offset++] << 8,
  85421. pixel_size: data[offset++],
  85422. flags: data[offset++]
  85423. };
  85424. return header;
  85425. };
  85426. TGATools.UploadContent = function (gl, data) {
  85427. // Not enough data to contain header ?
  85428. if (data.length < 19) {
  85429. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85430. return;
  85431. }
  85432. // Read Header
  85433. var offset = 18;
  85434. var header = TGATools.GetTGAHeader(data);
  85435. // Assume it's a valid Targa file.
  85436. if (header.id_length + offset > data.length) {
  85437. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85438. return;
  85439. }
  85440. // Skip not needed data
  85441. offset += header.id_length;
  85442. var use_rle = false;
  85443. var use_pal = false;
  85444. var use_grey = false;
  85445. // Get some informations.
  85446. switch (header.image_type) {
  85447. case TGATools._TYPE_RLE_INDEXED:
  85448. use_rle = true;
  85449. case TGATools._TYPE_INDEXED:
  85450. use_pal = true;
  85451. break;
  85452. case TGATools._TYPE_RLE_RGB:
  85453. use_rle = true;
  85454. case TGATools._TYPE_RGB:
  85455. // use_rgb = true;
  85456. break;
  85457. case TGATools._TYPE_RLE_GREY:
  85458. use_rle = true;
  85459. case TGATools._TYPE_GREY:
  85460. use_grey = true;
  85461. break;
  85462. }
  85463. var pixel_data;
  85464. // var numAlphaBits = header.flags & 0xf;
  85465. var pixel_size = header.pixel_size >> 3;
  85466. var pixel_total = header.width * header.height * pixel_size;
  85467. // Read palettes
  85468. var palettes;
  85469. if (use_pal) {
  85470. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  85471. }
  85472. // Read LRE
  85473. if (use_rle) {
  85474. pixel_data = new Uint8Array(pixel_total);
  85475. var c, count, i;
  85476. var localOffset = 0;
  85477. var pixels = new Uint8Array(pixel_size);
  85478. while (offset < pixel_total && localOffset < pixel_total) {
  85479. c = data[offset++];
  85480. count = (c & 0x7f) + 1;
  85481. // RLE pixels
  85482. if (c & 0x80) {
  85483. // Bind pixel tmp array
  85484. for (i = 0; i < pixel_size; ++i) {
  85485. pixels[i] = data[offset++];
  85486. }
  85487. // Copy pixel array
  85488. for (i = 0; i < count; ++i) {
  85489. pixel_data.set(pixels, localOffset + i * pixel_size);
  85490. }
  85491. localOffset += pixel_size * count;
  85492. }
  85493. // Raw pixels
  85494. else {
  85495. count *= pixel_size;
  85496. for (i = 0; i < count; ++i) {
  85497. pixel_data[localOffset + i] = data[offset++];
  85498. }
  85499. localOffset += count;
  85500. }
  85501. }
  85502. }
  85503. // RAW Pixels
  85504. else {
  85505. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  85506. }
  85507. // Load to texture
  85508. var x_start, y_start, x_step, y_step, y_end, x_end;
  85509. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  85510. default:
  85511. case TGATools._ORIGIN_UL:
  85512. x_start = 0;
  85513. x_step = 1;
  85514. x_end = header.width;
  85515. y_start = 0;
  85516. y_step = 1;
  85517. y_end = header.height;
  85518. break;
  85519. case TGATools._ORIGIN_BL:
  85520. x_start = 0;
  85521. x_step = 1;
  85522. x_end = header.width;
  85523. y_start = header.height - 1;
  85524. y_step = -1;
  85525. y_end = -1;
  85526. break;
  85527. case TGATools._ORIGIN_UR:
  85528. x_start = header.width - 1;
  85529. x_step = -1;
  85530. x_end = -1;
  85531. y_start = 0;
  85532. y_step = 1;
  85533. y_end = header.height;
  85534. break;
  85535. case TGATools._ORIGIN_BR:
  85536. x_start = header.width - 1;
  85537. x_step = -1;
  85538. x_end = -1;
  85539. y_start = header.height - 1;
  85540. y_step = -1;
  85541. y_end = -1;
  85542. break;
  85543. }
  85544. // Load the specify method
  85545. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  85546. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  85547. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  85548. };
  85549. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85550. var image = pixel_data, colormap = palettes;
  85551. var width = header.width, height = header.height;
  85552. var color, i = 0, x, y;
  85553. var imageData = new Uint8Array(width * height * 4);
  85554. for (y = y_start; y !== y_end; y += y_step) {
  85555. for (x = x_start; x !== x_end; x += x_step, i++) {
  85556. color = image[i];
  85557. imageData[(x + width * y) * 4 + 3] = 255;
  85558. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  85559. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  85560. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  85561. }
  85562. }
  85563. return imageData;
  85564. };
  85565. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85566. var image = pixel_data;
  85567. var width = header.width, height = header.height;
  85568. var color, i = 0, x, y;
  85569. var imageData = new Uint8Array(width * height * 4);
  85570. for (y = y_start; y !== y_end; y += y_step) {
  85571. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85572. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  85573. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  85574. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  85575. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  85576. imageData[(x + width * y) * 4 + 0] = r;
  85577. imageData[(x + width * y) * 4 + 1] = g;
  85578. imageData[(x + width * y) * 4 + 2] = b;
  85579. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  85580. }
  85581. }
  85582. return imageData;
  85583. };
  85584. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85585. var image = pixel_data;
  85586. var width = header.width, height = header.height;
  85587. var i = 0, x, y;
  85588. var imageData = new Uint8Array(width * height * 4);
  85589. for (y = y_start; y !== y_end; y += y_step) {
  85590. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  85591. imageData[(x + width * y) * 4 + 3] = 255;
  85592. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85593. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85594. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85595. }
  85596. }
  85597. return imageData;
  85598. };
  85599. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85600. var image = pixel_data;
  85601. var width = header.width, height = header.height;
  85602. var i = 0, x, y;
  85603. var imageData = new Uint8Array(width * height * 4);
  85604. for (y = y_start; y !== y_end; y += y_step) {
  85605. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  85606. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85607. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85608. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85609. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  85610. }
  85611. }
  85612. return imageData;
  85613. };
  85614. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85615. var image = pixel_data;
  85616. var width = header.width, height = header.height;
  85617. var color, i = 0, x, y;
  85618. var imageData = new Uint8Array(width * height * 4);
  85619. for (y = y_start; y !== y_end; y += y_step) {
  85620. for (x = x_start; x !== x_end; x += x_step, i++) {
  85621. color = image[i];
  85622. imageData[(x + width * y) * 4 + 0] = color;
  85623. imageData[(x + width * y) * 4 + 1] = color;
  85624. imageData[(x + width * y) * 4 + 2] = color;
  85625. imageData[(x + width * y) * 4 + 3] = 255;
  85626. }
  85627. }
  85628. return imageData;
  85629. };
  85630. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85631. var image = pixel_data;
  85632. var width = header.width, height = header.height;
  85633. var i = 0, x, y;
  85634. var imageData = new Uint8Array(width * height * 4);
  85635. for (y = y_start; y !== y_end; y += y_step) {
  85636. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85637. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  85638. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  85639. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85640. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  85641. }
  85642. }
  85643. return imageData;
  85644. };
  85645. //private static _TYPE_NO_DATA = 0;
  85646. TGATools._TYPE_INDEXED = 1;
  85647. TGATools._TYPE_RGB = 2;
  85648. TGATools._TYPE_GREY = 3;
  85649. TGATools._TYPE_RLE_INDEXED = 9;
  85650. TGATools._TYPE_RLE_RGB = 10;
  85651. TGATools._TYPE_RLE_GREY = 11;
  85652. TGATools._ORIGIN_MASK = 0x30;
  85653. TGATools._ORIGIN_SHIFT = 0x04;
  85654. TGATools._ORIGIN_BL = 0x00;
  85655. TGATools._ORIGIN_BR = 0x01;
  85656. TGATools._ORIGIN_UL = 0x02;
  85657. TGATools._ORIGIN_UR = 0x03;
  85658. return TGATools;
  85659. }());
  85660. BABYLON.TGATools = TGATools;
  85661. })(BABYLON || (BABYLON = {}));
  85662. //# sourceMappingURL=babylon.tga.js.map
  85663. var BABYLON;
  85664. (function (BABYLON) {
  85665. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  85666. // All values and structures referenced from:
  85667. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  85668. var DDS_MAGIC = 0x20534444;
  85669. var
  85670. //DDSD_CAPS = 0x1,
  85671. //DDSD_HEIGHT = 0x2,
  85672. //DDSD_WIDTH = 0x4,
  85673. //DDSD_PITCH = 0x8,
  85674. //DDSD_PIXELFORMAT = 0x1000,
  85675. DDSD_MIPMAPCOUNT = 0x20000;
  85676. //DDSD_LINEARSIZE = 0x80000,
  85677. //DDSD_DEPTH = 0x800000;
  85678. // var DDSCAPS_COMPLEX = 0x8,
  85679. // DDSCAPS_MIPMAP = 0x400000,
  85680. // DDSCAPS_TEXTURE = 0x1000;
  85681. var DDSCAPS2_CUBEMAP = 0x200;
  85682. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  85683. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  85684. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  85685. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  85686. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  85687. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  85688. // DDSCAPS2_VOLUME = 0x200000;
  85689. var
  85690. //DDPF_ALPHAPIXELS = 0x1,
  85691. //DDPF_ALPHA = 0x2,
  85692. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  85693. //DDPF_YUV = 0x200,
  85694. DDPF_LUMINANCE = 0x20000;
  85695. function FourCCToInt32(value) {
  85696. return value.charCodeAt(0) +
  85697. (value.charCodeAt(1) << 8) +
  85698. (value.charCodeAt(2) << 16) +
  85699. (value.charCodeAt(3) << 24);
  85700. }
  85701. function Int32ToFourCC(value) {
  85702. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  85703. }
  85704. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  85705. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  85706. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  85707. var FOURCC_DX10 = FourCCToInt32("DX10");
  85708. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  85709. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  85710. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  85711. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  85712. var headerLengthInt = 31; // The header length in 32 bit ints
  85713. // Offsets into the header array
  85714. var off_magic = 0;
  85715. var off_size = 1;
  85716. var off_flags = 2;
  85717. var off_height = 3;
  85718. var off_width = 4;
  85719. var off_mipmapCount = 7;
  85720. var off_pfFlags = 20;
  85721. var off_pfFourCC = 21;
  85722. var off_RGBbpp = 22;
  85723. var off_RMask = 23;
  85724. var off_GMask = 24;
  85725. var off_BMask = 25;
  85726. var off_AMask = 26;
  85727. // var off_caps1 = 27;
  85728. var off_caps2 = 28;
  85729. // var off_caps3 = 29;
  85730. // var off_caps4 = 30;
  85731. var off_dxgiFormat = 32;
  85732. ;
  85733. var DDSTools = /** @class */ (function () {
  85734. function DDSTools() {
  85735. }
  85736. DDSTools.GetDDSInfo = function (arrayBuffer) {
  85737. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85738. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  85739. var mipmapCount = 1;
  85740. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  85741. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85742. }
  85743. var fourCC = header[off_pfFourCC];
  85744. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  85745. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85746. switch (fourCC) {
  85747. case FOURCC_D3DFMT_R16G16B16A16F:
  85748. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85749. break;
  85750. case FOURCC_D3DFMT_R32G32B32A32F:
  85751. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85752. break;
  85753. case FOURCC_DX10:
  85754. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  85755. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85756. break;
  85757. }
  85758. }
  85759. return {
  85760. width: header[off_width],
  85761. height: header[off_height],
  85762. mipmapCount: mipmapCount,
  85763. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  85764. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  85765. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  85766. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  85767. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  85768. dxgiFormat: dxgiFormat,
  85769. textureType: textureType
  85770. };
  85771. };
  85772. DDSTools._ToHalfFloat = function (value) {
  85773. if (!DDSTools._FloatView) {
  85774. DDSTools._FloatView = new Float32Array(1);
  85775. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  85776. }
  85777. DDSTools._FloatView[0] = value;
  85778. var x = DDSTools._Int32View[0];
  85779. var bits = (x >> 16) & 0x8000; /* Get the sign */
  85780. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  85781. var e = (x >> 23) & 0xff; /* Using int is faster here */
  85782. /* If zero, or denormal, or exponent underflows too much for a denormal
  85783. * half, return signed zero. */
  85784. if (e < 103) {
  85785. return bits;
  85786. }
  85787. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  85788. if (e > 142) {
  85789. bits |= 0x7c00;
  85790. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  85791. * not Inf, so make sure we set one mantissa bit too. */
  85792. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  85793. return bits;
  85794. }
  85795. /* If exponent underflows but not too much, return a denormal */
  85796. if (e < 113) {
  85797. m |= 0x0800;
  85798. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85799. * to 1, which is OK. */
  85800. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85801. return bits;
  85802. }
  85803. bits |= ((e - 112) << 10) | (m >> 1);
  85804. bits += m & 1;
  85805. return bits;
  85806. };
  85807. DDSTools._FromHalfFloat = function (value) {
  85808. var s = (value & 0x8000) >> 15;
  85809. var e = (value & 0x7C00) >> 10;
  85810. var f = value & 0x03FF;
  85811. if (e === 0) {
  85812. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85813. }
  85814. else if (e == 0x1F) {
  85815. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85816. }
  85817. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85818. };
  85819. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85820. var destArray = new Float32Array(dataLength);
  85821. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85822. var index = 0;
  85823. for (var y = 0; y < height; y++) {
  85824. for (var x = 0; x < width; x++) {
  85825. var srcPos = (x + y * width) * 4;
  85826. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85827. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85828. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85829. if (DDSTools.StoreLODInAlphaChannel) {
  85830. destArray[index + 3] = lod;
  85831. }
  85832. else {
  85833. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85834. }
  85835. index += 4;
  85836. }
  85837. }
  85838. return destArray;
  85839. };
  85840. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85841. if (DDSTools.StoreLODInAlphaChannel) {
  85842. var destArray = new Uint16Array(dataLength);
  85843. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85844. var index = 0;
  85845. for (var y = 0; y < height; y++) {
  85846. for (var x = 0; x < width; x++) {
  85847. var srcPos = (x + y * width) * 4;
  85848. destArray[index] = srcData[srcPos];
  85849. destArray[index + 1] = srcData[srcPos + 1];
  85850. destArray[index + 2] = srcData[srcPos + 2];
  85851. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85852. index += 4;
  85853. }
  85854. }
  85855. return destArray;
  85856. }
  85857. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85858. };
  85859. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85860. if (DDSTools.StoreLODInAlphaChannel) {
  85861. var destArray = new Float32Array(dataLength);
  85862. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85863. var index = 0;
  85864. for (var y = 0; y < height; y++) {
  85865. for (var x = 0; x < width; x++) {
  85866. var srcPos = (x + y * width) * 4;
  85867. destArray[index] = srcData[srcPos];
  85868. destArray[index + 1] = srcData[srcPos + 1];
  85869. destArray[index + 2] = srcData[srcPos + 2];
  85870. destArray[index + 3] = lod;
  85871. index += 4;
  85872. }
  85873. }
  85874. return destArray;
  85875. }
  85876. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85877. };
  85878. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85879. var destArray = new Uint8Array(dataLength);
  85880. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85881. var index = 0;
  85882. for (var y = 0; y < height; y++) {
  85883. for (var x = 0; x < width; x++) {
  85884. var srcPos = (x + y * width) * 4;
  85885. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85886. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85887. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85888. if (DDSTools.StoreLODInAlphaChannel) {
  85889. destArray[index + 3] = lod;
  85890. }
  85891. else {
  85892. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85893. }
  85894. index += 4;
  85895. }
  85896. }
  85897. return destArray;
  85898. };
  85899. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85900. var destArray = new Uint8Array(dataLength);
  85901. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85902. var index = 0;
  85903. for (var y = 0; y < height; y++) {
  85904. for (var x = 0; x < width; x++) {
  85905. var srcPos = (x + y * width) * 4;
  85906. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85907. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85908. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85909. if (DDSTools.StoreLODInAlphaChannel) {
  85910. destArray[index + 3] = lod;
  85911. }
  85912. else {
  85913. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85914. }
  85915. index += 4;
  85916. }
  85917. }
  85918. return destArray;
  85919. };
  85920. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85921. var byteArray = new Uint8Array(dataLength);
  85922. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85923. var index = 0;
  85924. for (var y = 0; y < height; y++) {
  85925. for (var x = 0; x < width; x++) {
  85926. var srcPos = (x + y * width) * 4;
  85927. byteArray[index] = srcData[srcPos + rOffset];
  85928. byteArray[index + 1] = srcData[srcPos + gOffset];
  85929. byteArray[index + 2] = srcData[srcPos + bOffset];
  85930. byteArray[index + 3] = srcData[srcPos + aOffset];
  85931. index += 4;
  85932. }
  85933. }
  85934. return byteArray;
  85935. };
  85936. DDSTools._ExtractLongWordOrder = function (value) {
  85937. if (value === 0 || value === 255 || value === -16777216) {
  85938. return 0;
  85939. }
  85940. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85941. };
  85942. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85943. var byteArray = new Uint8Array(dataLength);
  85944. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85945. var index = 0;
  85946. for (var y = 0; y < height; y++) {
  85947. for (var x = 0; x < width; x++) {
  85948. var srcPos = (x + y * width) * 3;
  85949. byteArray[index] = srcData[srcPos + rOffset];
  85950. byteArray[index + 1] = srcData[srcPos + gOffset];
  85951. byteArray[index + 2] = srcData[srcPos + bOffset];
  85952. index += 3;
  85953. }
  85954. }
  85955. return byteArray;
  85956. };
  85957. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85958. var byteArray = new Uint8Array(dataLength);
  85959. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85960. var index = 0;
  85961. for (var y = 0; y < height; y++) {
  85962. for (var x = 0; x < width; x++) {
  85963. var srcPos = (x + y * width);
  85964. byteArray[index] = srcData[srcPos];
  85965. index++;
  85966. }
  85967. }
  85968. return byteArray;
  85969. };
  85970. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85971. if (lodIndex === void 0) { lodIndex = -1; }
  85972. var sphericalPolynomialFaces = null;
  85973. if (info.sphericalPolynomial) {
  85974. sphericalPolynomialFaces = new Array();
  85975. }
  85976. var ext = engine.getCaps().s3tc;
  85977. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85978. var fourCC, width, height, dataLength = 0, dataOffset;
  85979. var byteArray, mipmapCount, mip;
  85980. var internalFormat = 0;
  85981. var format = 0;
  85982. var blockBytes = 1;
  85983. if (header[off_magic] !== DDS_MAGIC) {
  85984. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85985. return;
  85986. }
  85987. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85988. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85989. return;
  85990. }
  85991. if (info.isCompressed && !ext) {
  85992. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85993. return;
  85994. }
  85995. var bpp = header[off_RGBbpp];
  85996. dataOffset = header[off_size] + 4;
  85997. var computeFormats = false;
  85998. if (info.isFourCC) {
  85999. fourCC = header[off_pfFourCC];
  86000. switch (fourCC) {
  86001. case FOURCC_DXT1:
  86002. blockBytes = 8;
  86003. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86004. break;
  86005. case FOURCC_DXT3:
  86006. blockBytes = 16;
  86007. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86008. break;
  86009. case FOURCC_DXT5:
  86010. blockBytes = 16;
  86011. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86012. break;
  86013. case FOURCC_D3DFMT_R16G16B16A16F:
  86014. computeFormats = true;
  86015. break;
  86016. case FOURCC_D3DFMT_R32G32B32A32F:
  86017. computeFormats = true;
  86018. break;
  86019. case FOURCC_DX10:
  86020. // There is an additionnal header so dataOffset need to be changed
  86021. dataOffset += 5 * 4; // 5 uints
  86022. var supported = false;
  86023. switch (info.dxgiFormat) {
  86024. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86025. computeFormats = true;
  86026. supported = true;
  86027. break;
  86028. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86029. info.isRGB = true;
  86030. info.isFourCC = false;
  86031. bpp = 32;
  86032. supported = true;
  86033. break;
  86034. }
  86035. if (supported) {
  86036. break;
  86037. }
  86038. default:
  86039. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86040. return;
  86041. }
  86042. }
  86043. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86044. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86045. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86046. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86047. if (computeFormats) {
  86048. format = engine._getWebGLTextureType(info.textureType);
  86049. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86050. }
  86051. mipmapCount = 1;
  86052. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86053. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86054. }
  86055. for (var face = 0; face < faces; face++) {
  86056. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86057. width = header[off_width];
  86058. height = header[off_height];
  86059. for (mip = 0; mip < mipmapCount; ++mip) {
  86060. if (lodIndex === -1 || lodIndex === mip) {
  86061. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86062. var i = (lodIndex === -1) ? mip : 0;
  86063. if (!info.isCompressed && info.isFourCC) {
  86064. dataLength = width * height * 4;
  86065. var floatArray = null;
  86066. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86067. if (bpp === 128) {
  86068. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86069. if (sphericalPolynomialFaces && i == 0) {
  86070. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86071. }
  86072. }
  86073. else if (bpp === 64) {
  86074. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86075. if (sphericalPolynomialFaces && i == 0) {
  86076. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86077. }
  86078. }
  86079. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86080. format = engine._getWebGLTextureType(info.textureType);
  86081. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86082. }
  86083. else {
  86084. if (bpp === 128) {
  86085. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86086. if (sphericalPolynomialFaces && i == 0) {
  86087. sphericalPolynomialFaces.push(floatArray);
  86088. }
  86089. }
  86090. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86091. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86092. if (sphericalPolynomialFaces && i == 0) {
  86093. sphericalPolynomialFaces.push(floatArray);
  86094. }
  86095. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86096. format = engine._getWebGLTextureType(info.textureType);
  86097. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86098. }
  86099. else { // 64
  86100. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86101. if (sphericalPolynomialFaces && i == 0) {
  86102. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86103. }
  86104. }
  86105. }
  86106. if (floatArray) {
  86107. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86108. }
  86109. }
  86110. else if (info.isRGB) {
  86111. if (bpp === 24) {
  86112. dataLength = width * height * 3;
  86113. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86114. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86115. }
  86116. else { // 32
  86117. dataLength = width * height * 4;
  86118. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86119. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86120. }
  86121. }
  86122. else if (info.isLuminance) {
  86123. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86124. var unpaddedRowSize = width;
  86125. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86126. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86127. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86128. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86129. }
  86130. else {
  86131. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86132. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86133. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86134. }
  86135. }
  86136. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86137. width *= 0.5;
  86138. height *= 0.5;
  86139. width = Math.max(1.0, width);
  86140. height = Math.max(1.0, height);
  86141. }
  86142. if (currentFace !== undefined) {
  86143. // Loading a single face
  86144. break;
  86145. }
  86146. }
  86147. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86148. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86149. size: header[off_width],
  86150. right: sphericalPolynomialFaces[0],
  86151. left: sphericalPolynomialFaces[1],
  86152. up: sphericalPolynomialFaces[2],
  86153. down: sphericalPolynomialFaces[3],
  86154. front: sphericalPolynomialFaces[4],
  86155. back: sphericalPolynomialFaces[5],
  86156. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86157. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86158. gammaSpace: false,
  86159. });
  86160. }
  86161. else {
  86162. info.sphericalPolynomial = undefined;
  86163. }
  86164. };
  86165. DDSTools.StoreLODInAlphaChannel = false;
  86166. return DDSTools;
  86167. }());
  86168. BABYLON.DDSTools = DDSTools;
  86169. })(BABYLON || (BABYLON = {}));
  86170. //# sourceMappingURL=babylon.dds.js.map
  86171. var BABYLON;
  86172. (function (BABYLON) {
  86173. /**
  86174. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86175. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86176. */
  86177. var KhronosTextureContainer = /** @class */ (function () {
  86178. /**
  86179. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86180. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86181. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86182. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86183. */
  86184. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86185. this.arrayBuffer = arrayBuffer;
  86186. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86187. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86188. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86189. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86190. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86191. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86192. BABYLON.Tools.Error("texture missing KTX identifier");
  86193. return;
  86194. }
  86195. // load the reset of the header in native 32 bit int
  86196. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86197. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86198. var oppositeEndianess = header[0] === 0x01020304;
  86199. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86200. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86201. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86202. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86203. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86204. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86205. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86206. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86207. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86208. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86209. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86210. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86211. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86212. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86213. if (this.glType !== 0) {
  86214. BABYLON.Tools.Error("only compressed formats currently supported");
  86215. return;
  86216. }
  86217. else {
  86218. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86219. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86220. }
  86221. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86222. BABYLON.Tools.Error("only 2D textures currently supported");
  86223. return;
  86224. }
  86225. if (this.numberOfArrayElements !== 0) {
  86226. BABYLON.Tools.Error("texture arrays not currently supported");
  86227. return;
  86228. }
  86229. if (this.numberOfFaces !== facesExpected) {
  86230. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86231. return;
  86232. }
  86233. // we now have a completely validated file, so could use existence of loadType as success
  86234. // would need to make this more elaborate & adjust checks above to support more than one load type
  86235. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86236. }
  86237. // not as fast hardware based, but will probably never need to use
  86238. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86239. return ((val & 0xFF) << 24)
  86240. | ((val & 0xFF00) << 8)
  86241. | ((val >> 8) & 0xFF00)
  86242. | ((val >> 24) & 0xFF);
  86243. };
  86244. /**
  86245. * It is assumed that the texture has already been created & is currently bound
  86246. */
  86247. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86248. switch (this.loadType) {
  86249. case KhronosTextureContainer.COMPRESSED_2D:
  86250. this._upload2DCompressedLevels(gl, loadMipmaps);
  86251. break;
  86252. case KhronosTextureContainer.TEX_2D:
  86253. case KhronosTextureContainer.COMPRESSED_3D:
  86254. case KhronosTextureContainer.TEX_3D:
  86255. }
  86256. };
  86257. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86258. // initialize width & height for level 1
  86259. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86260. var width = this.pixelWidth;
  86261. var height = this.pixelHeight;
  86262. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86263. for (var level = 0; level < mipmapCount; level++) {
  86264. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86265. for (var face = 0; face < this.numberOfFaces; face++) {
  86266. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86267. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86268. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86269. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86270. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86271. }
  86272. width = Math.max(1.0, width * 0.5);
  86273. height = Math.max(1.0, height * 0.5);
  86274. }
  86275. };
  86276. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86277. // load types
  86278. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86279. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86280. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86281. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86282. return KhronosTextureContainer;
  86283. }());
  86284. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86285. })(BABYLON || (BABYLON = {}));
  86286. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86287. var BABYLON;
  86288. (function (BABYLON) {
  86289. var Debug;
  86290. (function (Debug) {
  86291. /**
  86292. * Class used to render a debug view of a given skeleton
  86293. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86294. */
  86295. var SkeletonViewer = /** @class */ (function () {
  86296. /**
  86297. * Creates a new SkeletonViewer
  86298. * @param skeleton defines the skeleton to render
  86299. * @param mesh defines the mesh attached to the skeleton
  86300. * @param scene defines the hosting scene
  86301. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86302. * @param renderingGroupId defines the rendering group id to use with the viewer
  86303. */
  86304. function SkeletonViewer(
  86305. /** defines the skeleton to render */
  86306. skeleton,
  86307. /** defines the mesh attached to the skeleton */
  86308. mesh, scene,
  86309. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86310. autoUpdateBonesMatrices,
  86311. /** defines the rendering group id to use with the viewer */
  86312. renderingGroupId) {
  86313. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86314. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86315. this.skeleton = skeleton;
  86316. this.mesh = mesh;
  86317. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86318. this.renderingGroupId = renderingGroupId;
  86319. /** Gets or sets the color used to render the skeleton */
  86320. this.color = BABYLON.Color3.White();
  86321. this._debugLines = new Array();
  86322. this._isEnabled = false;
  86323. this._scene = scene;
  86324. this.update();
  86325. this._renderFunction = this.update.bind(this);
  86326. }
  86327. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86328. get: function () {
  86329. return this._isEnabled;
  86330. },
  86331. /** Gets or sets a boolean indicating if the viewer is enabled */
  86332. set: function (value) {
  86333. if (this._isEnabled === value) {
  86334. return;
  86335. }
  86336. this._isEnabled = value;
  86337. if (value) {
  86338. this._scene.registerBeforeRender(this._renderFunction);
  86339. }
  86340. else {
  86341. this._scene.unregisterBeforeRender(this._renderFunction);
  86342. }
  86343. },
  86344. enumerable: true,
  86345. configurable: true
  86346. });
  86347. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86348. if (x === void 0) { x = 0; }
  86349. if (y === void 0) { y = 0; }
  86350. if (z === void 0) { z = 0; }
  86351. var tmat = BABYLON.Tmp.Matrix[0];
  86352. var parentBone = bone.getParent();
  86353. tmat.copyFrom(bone.getLocalMatrix());
  86354. if (x !== 0 || y !== 0 || z !== 0) {
  86355. var tmat2 = BABYLON.Tmp.Matrix[1];
  86356. BABYLON.Matrix.IdentityToRef(tmat2);
  86357. tmat2.m[12] = x;
  86358. tmat2.m[13] = y;
  86359. tmat2.m[14] = z;
  86360. tmat2.multiplyToRef(tmat, tmat);
  86361. }
  86362. if (parentBone) {
  86363. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86364. }
  86365. tmat.multiplyToRef(meshMat, tmat);
  86366. position.x = tmat.m[12];
  86367. position.y = tmat.m[13];
  86368. position.z = tmat.m[14];
  86369. };
  86370. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86371. var len = bones.length;
  86372. var meshPos = this.mesh.position;
  86373. for (var i = 0; i < len; i++) {
  86374. var bone = bones[i];
  86375. var points = this._debugLines[i];
  86376. if (!points) {
  86377. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86378. this._debugLines[i] = points;
  86379. }
  86380. this._getBonePosition(points[0], bone, meshMat);
  86381. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86382. points[0].subtractInPlace(meshPos);
  86383. points[1].subtractInPlace(meshPos);
  86384. }
  86385. };
  86386. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86387. var len = bones.length;
  86388. var boneNum = 0;
  86389. var meshPos = this.mesh.position;
  86390. for (var i = len - 1; i >= 0; i--) {
  86391. var childBone = bones[i];
  86392. var parentBone = childBone.getParent();
  86393. if (!parentBone) {
  86394. continue;
  86395. }
  86396. var points = this._debugLines[boneNum];
  86397. if (!points) {
  86398. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86399. this._debugLines[boneNum] = points;
  86400. }
  86401. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86402. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86403. points[0].subtractInPlace(meshPos);
  86404. points[1].subtractInPlace(meshPos);
  86405. boneNum++;
  86406. }
  86407. };
  86408. /** Update the viewer to sync with current skeleton state */
  86409. SkeletonViewer.prototype.update = function () {
  86410. if (this.autoUpdateBonesMatrices) {
  86411. this.skeleton.computeAbsoluteTransforms();
  86412. }
  86413. if (this.skeleton.bones[0].length === undefined) {
  86414. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86415. }
  86416. else {
  86417. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86418. }
  86419. if (!this._debugMesh) {
  86420. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86421. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86422. }
  86423. else {
  86424. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86425. }
  86426. this._debugMesh.position.copyFrom(this.mesh.position);
  86427. this._debugMesh.color = this.color;
  86428. };
  86429. /** Release associated resources */
  86430. SkeletonViewer.prototype.dispose = function () {
  86431. if (this._debugMesh) {
  86432. this.isEnabled = false;
  86433. this._debugMesh.dispose();
  86434. this._debugMesh = null;
  86435. }
  86436. };
  86437. return SkeletonViewer;
  86438. }());
  86439. Debug.SkeletonViewer = SkeletonViewer;
  86440. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86441. })(BABYLON || (BABYLON = {}));
  86442. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86443. /**
  86444. * Module Debug contains the (visual) components to debug a scene correctly
  86445. */
  86446. var BABYLON;
  86447. (function (BABYLON) {
  86448. var Debug;
  86449. (function (Debug) {
  86450. /**
  86451. * The Axes viewer will show 3 axes in a specific point in space
  86452. */
  86453. var AxesViewer = /** @class */ (function () {
  86454. /**
  86455. * Creates a new AxesViewer
  86456. * @param scene defines the hosting scene
  86457. * @param scaleLines defines a number used to scale line length (1 by default)
  86458. */
  86459. function AxesViewer(scene, scaleLines) {
  86460. if (scaleLines === void 0) { scaleLines = 1; }
  86461. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86462. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86463. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86464. /**
  86465. * Gets or sets a number used to scale line length
  86466. */
  86467. this.scaleLines = 1;
  86468. this.scaleLines = scaleLines;
  86469. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  86470. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  86471. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  86472. this._xmesh.renderingGroupId = 2;
  86473. this._ymesh.renderingGroupId = 2;
  86474. this._zmesh.renderingGroupId = 2;
  86475. this._xmesh.material.checkReadyOnlyOnce = true;
  86476. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  86477. this._ymesh.material.checkReadyOnlyOnce = true;
  86478. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  86479. this._zmesh.material.checkReadyOnlyOnce = true;
  86480. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  86481. this.scene = scene;
  86482. }
  86483. /**
  86484. * Force the viewer to update
  86485. * @param position defines the position of the viewer
  86486. * @param xaxis defines the x axis of the viewer
  86487. * @param yaxis defines the y axis of the viewer
  86488. * @param zaxis defines the z axis of the viewer
  86489. */
  86490. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  86491. var scaleLines = this.scaleLines;
  86492. if (this._xmesh) {
  86493. this._xmesh.position.copyFrom(position);
  86494. }
  86495. if (this._ymesh) {
  86496. this._ymesh.position.copyFrom(position);
  86497. }
  86498. if (this._zmesh) {
  86499. this._zmesh.position.copyFrom(position);
  86500. }
  86501. var point2 = this._xline[1];
  86502. point2.x = xaxis.x * scaleLines;
  86503. point2.y = xaxis.y * scaleLines;
  86504. point2.z = xaxis.z * scaleLines;
  86505. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  86506. point2 = this._yline[1];
  86507. point2.x = yaxis.x * scaleLines;
  86508. point2.y = yaxis.y * scaleLines;
  86509. point2.z = yaxis.z * scaleLines;
  86510. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  86511. point2 = this._zline[1];
  86512. point2.x = zaxis.x * scaleLines;
  86513. point2.y = zaxis.y * scaleLines;
  86514. point2.z = zaxis.z * scaleLines;
  86515. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  86516. };
  86517. /** Releases resources */
  86518. AxesViewer.prototype.dispose = function () {
  86519. if (this._xmesh) {
  86520. this._xmesh.dispose();
  86521. }
  86522. if (this._ymesh) {
  86523. this._ymesh.dispose();
  86524. }
  86525. if (this._zmesh) {
  86526. this._zmesh.dispose();
  86527. }
  86528. this._xmesh = null;
  86529. this._ymesh = null;
  86530. this._zmesh = null;
  86531. this.scene = null;
  86532. };
  86533. return AxesViewer;
  86534. }());
  86535. Debug.AxesViewer = AxesViewer;
  86536. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86537. })(BABYLON || (BABYLON = {}));
  86538. //# sourceMappingURL=babylon.axesViewer.js.map
  86539. var BABYLON;
  86540. (function (BABYLON) {
  86541. var Debug;
  86542. (function (Debug) {
  86543. /**
  86544. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  86545. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  86546. */
  86547. var BoneAxesViewer = /** @class */ (function (_super) {
  86548. __extends(BoneAxesViewer, _super);
  86549. /**
  86550. * Creates a new BoneAxesViewer
  86551. * @param scene defines the hosting scene
  86552. * @param bone defines the target bone
  86553. * @param mesh defines the target mesh
  86554. * @param scaleLines defines a scaling factor for line length (1 by default)
  86555. */
  86556. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  86557. if (scaleLines === void 0) { scaleLines = 1; }
  86558. var _this = _super.call(this, scene, scaleLines) || this;
  86559. /** Gets current position */
  86560. _this.pos = BABYLON.Vector3.Zero();
  86561. /** Gets direction of X axis */
  86562. _this.xaxis = BABYLON.Vector3.Zero();
  86563. /** Gets direction of Y axis */
  86564. _this.yaxis = BABYLON.Vector3.Zero();
  86565. /** Gets direction of Z axis */
  86566. _this.zaxis = BABYLON.Vector3.Zero();
  86567. _this.mesh = mesh;
  86568. _this.bone = bone;
  86569. return _this;
  86570. }
  86571. /**
  86572. * Force the viewer to update
  86573. */
  86574. BoneAxesViewer.prototype.update = function () {
  86575. if (!this.mesh || !this.bone) {
  86576. return;
  86577. }
  86578. var bone = this.bone;
  86579. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  86580. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  86581. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  86582. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  86583. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  86584. };
  86585. /** Releases resources */
  86586. BoneAxesViewer.prototype.dispose = function () {
  86587. if (this.mesh) {
  86588. this.mesh = null;
  86589. this.bone = null;
  86590. _super.prototype.dispose.call(this);
  86591. }
  86592. };
  86593. return BoneAxesViewer;
  86594. }(Debug.AxesViewer));
  86595. Debug.BoneAxesViewer = BoneAxesViewer;
  86596. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86597. })(BABYLON || (BABYLON = {}));
  86598. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  86599. var BABYLON;
  86600. (function (BABYLON) {
  86601. var RayHelper = /** @class */ (function () {
  86602. function RayHelper(ray) {
  86603. this.ray = ray;
  86604. }
  86605. RayHelper.CreateAndShow = function (ray, scene, color) {
  86606. var helper = new RayHelper(ray);
  86607. helper.show(scene, color);
  86608. return helper;
  86609. };
  86610. RayHelper.prototype.show = function (scene, color) {
  86611. if (!this._renderFunction && this.ray) {
  86612. var ray = this.ray;
  86613. this._renderFunction = this._render.bind(this);
  86614. this._scene = scene;
  86615. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  86616. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  86617. if (this._renderFunction) {
  86618. this._scene.registerBeforeRender(this._renderFunction);
  86619. }
  86620. }
  86621. if (color && this._renderLine) {
  86622. this._renderLine.color.copyFrom(color);
  86623. }
  86624. };
  86625. RayHelper.prototype.hide = function () {
  86626. if (this._renderFunction && this._scene) {
  86627. this._scene.unregisterBeforeRender(this._renderFunction);
  86628. this._scene = null;
  86629. this._renderFunction = null;
  86630. if (this._renderLine) {
  86631. this._renderLine.dispose();
  86632. this._renderLine = null;
  86633. }
  86634. this._renderPoints = [];
  86635. }
  86636. };
  86637. RayHelper.prototype._render = function () {
  86638. var ray = this.ray;
  86639. if (!ray) {
  86640. return;
  86641. }
  86642. var point = this._renderPoints[1];
  86643. var len = Math.min(ray.length, 1000000);
  86644. point.copyFrom(ray.direction);
  86645. point.scaleInPlace(len);
  86646. point.addInPlace(ray.origin);
  86647. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  86648. };
  86649. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  86650. this._attachedToMesh = mesh;
  86651. var ray = this.ray;
  86652. if (!ray) {
  86653. return;
  86654. }
  86655. if (!ray.direction) {
  86656. ray.direction = BABYLON.Vector3.Zero();
  86657. }
  86658. if (!ray.origin) {
  86659. ray.origin = BABYLON.Vector3.Zero();
  86660. }
  86661. if (length) {
  86662. ray.length = length;
  86663. }
  86664. if (!meshSpaceOrigin) {
  86665. meshSpaceOrigin = BABYLON.Vector3.Zero();
  86666. }
  86667. if (!meshSpaceDirection) {
  86668. // -1 so that this will work with Mesh.lookAt
  86669. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  86670. }
  86671. if (!this._meshSpaceDirection) {
  86672. this._meshSpaceDirection = meshSpaceDirection.clone();
  86673. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  86674. }
  86675. else {
  86676. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  86677. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  86678. }
  86679. if (!this._updateToMeshFunction) {
  86680. this._updateToMeshFunction = this._updateToMesh.bind(this);
  86681. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  86682. }
  86683. this._updateToMesh();
  86684. };
  86685. RayHelper.prototype.detachFromMesh = function () {
  86686. if (this._attachedToMesh) {
  86687. if (this._updateToMeshFunction) {
  86688. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  86689. }
  86690. this._attachedToMesh = null;
  86691. this._updateToMeshFunction = null;
  86692. }
  86693. };
  86694. RayHelper.prototype._updateToMesh = function () {
  86695. var ray = this.ray;
  86696. if (!this._attachedToMesh || !ray) {
  86697. return;
  86698. }
  86699. if (this._attachedToMesh._isDisposed) {
  86700. this.detachFromMesh();
  86701. return;
  86702. }
  86703. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  86704. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  86705. };
  86706. RayHelper.prototype.dispose = function () {
  86707. this.hide();
  86708. this.detachFromMesh();
  86709. this.ray = null;
  86710. };
  86711. return RayHelper;
  86712. }());
  86713. BABYLON.RayHelper = RayHelper;
  86714. })(BABYLON || (BABYLON = {}));
  86715. //# sourceMappingURL=babylon.rayHelper.js.map
  86716. var BABYLON;
  86717. (function (BABYLON) {
  86718. // load the inspector using require, if not present in the global namespace.
  86719. var DebugLayer = /** @class */ (function () {
  86720. function DebugLayer(scene) {
  86721. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86722. this._scene = scene;
  86723. // load inspector using require, if it doesn't exist on the global namespace.
  86724. }
  86725. /** Creates the inspector window. */
  86726. DebugLayer.prototype._createInspector = function (config) {
  86727. if (config === void 0) { config = {}; }
  86728. var popup = config.popup || false;
  86729. var initialTab = config.initialTab || 0;
  86730. var parentElement = config.parentElement || null;
  86731. if (!this._inspector) {
  86732. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86733. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  86734. } // else nothing to do,; instance is already existing
  86735. };
  86736. DebugLayer.prototype.isVisible = function () {
  86737. if (!this._inspector) {
  86738. return false;
  86739. }
  86740. return true;
  86741. };
  86742. DebugLayer.prototype.hide = function () {
  86743. if (this._inspector) {
  86744. try {
  86745. this._inspector.dispose();
  86746. }
  86747. catch (e) {
  86748. // If the inspector has been removed directly from the inspector tool
  86749. }
  86750. this.onPropertyChangedObservable.clear();
  86751. this._inspector = null;
  86752. }
  86753. };
  86754. /**
  86755. *
  86756. * Launch the debugLayer.
  86757. *
  86758. * initialTab:
  86759. * | Value | Tab Name |
  86760. * | --- | --- |
  86761. * | 0 | Scene |
  86762. * | 1 | Console |
  86763. * | 2 | Stats |
  86764. * | 3 | Textures |
  86765. * | 4 | Mesh |
  86766. * | 5 | Light |
  86767. * | 6 | Material |
  86768. * | 7 | GLTF |
  86769. * | 8 | GUI |
  86770. * | 9 | Physics |
  86771. * | 10 | Camera |
  86772. * | 11 | Audio |
  86773. *
  86774. */
  86775. DebugLayer.prototype.show = function (config) {
  86776. if (config === void 0) { config = {}; }
  86777. if (typeof this.BJSINSPECTOR == 'undefined') {
  86778. // Load inspector and add it to the DOM
  86779. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  86780. }
  86781. else {
  86782. // Otherwise creates the inspector
  86783. this._createInspector(config);
  86784. this.onPropertyChangedObservable = new BABYLON.Observable();
  86785. }
  86786. };
  86787. /**
  86788. * Gets the active tab
  86789. * @return the index of the active tab or -1 if the inspector is hidden
  86790. */
  86791. DebugLayer.prototype.getActiveTab = function () {
  86792. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  86793. };
  86794. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  86795. return DebugLayer;
  86796. }());
  86797. BABYLON.DebugLayer = DebugLayer;
  86798. })(BABYLON || (BABYLON = {}));
  86799. //# sourceMappingURL=babylon.debugLayer.js.map
  86800. var BABYLON;
  86801. (function (BABYLON) {
  86802. var Debug;
  86803. (function (Debug) {
  86804. /**
  86805. * Used to show the physics impostor around the specific mesh
  86806. */
  86807. var PhysicsViewer = /** @class */ (function () {
  86808. /**
  86809. * Creates a new PhysicsViewer
  86810. * @param scene defines the hosting scene
  86811. */
  86812. function PhysicsViewer(scene) {
  86813. /** @hidden */
  86814. this._impostors = [];
  86815. /** @hidden */
  86816. this._meshes = [];
  86817. /** @hidden */
  86818. this._numMeshes = 0;
  86819. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86820. var physicEngine = this._scene.getPhysicsEngine();
  86821. if (physicEngine) {
  86822. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  86823. }
  86824. }
  86825. /** @hidden */
  86826. PhysicsViewer.prototype._updateDebugMeshes = function () {
  86827. var plugin = this._physicsEnginePlugin;
  86828. for (var i = 0; i < this._numMeshes; i++) {
  86829. var impostor = this._impostors[i];
  86830. if (!impostor) {
  86831. continue;
  86832. }
  86833. if (impostor.isDisposed) {
  86834. this.hideImpostor(this._impostors[i--]);
  86835. }
  86836. else {
  86837. var mesh = this._meshes[i];
  86838. if (mesh && plugin) {
  86839. plugin.syncMeshWithImpostor(mesh, impostor);
  86840. }
  86841. }
  86842. }
  86843. };
  86844. /**
  86845. * Renders a specified physic impostor
  86846. * @param impostor defines the impostor to render
  86847. */
  86848. PhysicsViewer.prototype.showImpostor = function (impostor) {
  86849. if (!this._scene) {
  86850. return;
  86851. }
  86852. for (var i = 0; i < this._numMeshes; i++) {
  86853. if (this._impostors[i] == impostor) {
  86854. return;
  86855. }
  86856. }
  86857. var debugMesh = this._getDebugMesh(impostor, this._scene);
  86858. if (debugMesh) {
  86859. this._impostors[this._numMeshes] = impostor;
  86860. this._meshes[this._numMeshes] = debugMesh;
  86861. if (this._numMeshes === 0) {
  86862. this._renderFunction = this._updateDebugMeshes.bind(this);
  86863. this._scene.registerBeforeRender(this._renderFunction);
  86864. }
  86865. this._numMeshes++;
  86866. }
  86867. };
  86868. /**
  86869. * Hides a specified physic impostor
  86870. * @param impostor defines the impostor to hide
  86871. */
  86872. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  86873. if (!impostor || !this._scene) {
  86874. return;
  86875. }
  86876. var removed = false;
  86877. for (var i = 0; i < this._numMeshes; i++) {
  86878. if (this._impostors[i] == impostor) {
  86879. var mesh = this._meshes[i];
  86880. if (!mesh) {
  86881. continue;
  86882. }
  86883. this._scene.removeMesh(mesh);
  86884. mesh.dispose();
  86885. this._numMeshes--;
  86886. if (this._numMeshes > 0) {
  86887. this._meshes[i] = this._meshes[this._numMeshes];
  86888. this._impostors[i] = this._impostors[this._numMeshes];
  86889. this._meshes[this._numMeshes] = null;
  86890. this._impostors[this._numMeshes] = null;
  86891. }
  86892. else {
  86893. this._meshes[0] = null;
  86894. this._impostors[0] = null;
  86895. }
  86896. removed = true;
  86897. break;
  86898. }
  86899. }
  86900. if (removed && this._numMeshes === 0) {
  86901. this._scene.unregisterBeforeRender(this._renderFunction);
  86902. }
  86903. };
  86904. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86905. if (!this._debugMaterial) {
  86906. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86907. this._debugMaterial.wireframe = true;
  86908. }
  86909. return this._debugMaterial;
  86910. };
  86911. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86912. if (!this._debugBoxMesh) {
  86913. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86914. this._debugBoxMesh.renderingGroupId = 1;
  86915. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86916. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86917. scene.removeMesh(this._debugBoxMesh);
  86918. }
  86919. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86920. };
  86921. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86922. if (!this._debugSphereMesh) {
  86923. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86924. this._debugSphereMesh.renderingGroupId = 1;
  86925. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86926. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86927. scene.removeMesh(this._debugSphereMesh);
  86928. }
  86929. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86930. };
  86931. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86932. var mesh = null;
  86933. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86934. mesh = this._getDebugBoxMesh(scene);
  86935. impostor.getBoxSizeToRef(mesh.scaling);
  86936. }
  86937. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86938. mesh = this._getDebugSphereMesh(scene);
  86939. var radius = impostor.getRadius();
  86940. mesh.scaling.x = radius * 2;
  86941. mesh.scaling.y = radius * 2;
  86942. mesh.scaling.z = radius * 2;
  86943. }
  86944. return mesh;
  86945. };
  86946. /** Releases all resources */
  86947. PhysicsViewer.prototype.dispose = function () {
  86948. for (var i = 0; i < this._numMeshes; i++) {
  86949. this.hideImpostor(this._impostors[i]);
  86950. }
  86951. if (this._debugBoxMesh) {
  86952. this._debugBoxMesh.dispose();
  86953. }
  86954. if (this._debugSphereMesh) {
  86955. this._debugSphereMesh.dispose();
  86956. }
  86957. if (this._debugMaterial) {
  86958. this._debugMaterial.dispose();
  86959. }
  86960. this._impostors.length = 0;
  86961. this._scene = null;
  86962. this._physicsEnginePlugin = null;
  86963. };
  86964. return PhysicsViewer;
  86965. }());
  86966. Debug.PhysicsViewer = PhysicsViewer;
  86967. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86968. })(BABYLON || (BABYLON = {}));
  86969. //# sourceMappingURL=babylon.physicsViewer.js.map
  86970. var BABYLON;
  86971. (function (BABYLON) {
  86972. var BoundingBoxRenderer = /** @class */ (function () {
  86973. function BoundingBoxRenderer(scene) {
  86974. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86975. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86976. this.showBackLines = true;
  86977. this.renderList = new BABYLON.SmartArray(32);
  86978. this._vertexBuffers = {};
  86979. this._scene = scene;
  86980. }
  86981. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86982. if (this._colorShader) {
  86983. return;
  86984. }
  86985. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86986. attributes: [BABYLON.VertexBuffer.PositionKind],
  86987. uniforms: ["world", "viewProjection", "color"]
  86988. });
  86989. var engine = this._scene.getEngine();
  86990. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86991. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86992. this._createIndexBuffer();
  86993. };
  86994. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86995. var engine = this._scene.getEngine();
  86996. 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]);
  86997. };
  86998. BoundingBoxRenderer.prototype._rebuild = function () {
  86999. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87000. if (vb) {
  87001. vb._rebuild();
  87002. }
  87003. this._createIndexBuffer();
  87004. };
  87005. BoundingBoxRenderer.prototype.reset = function () {
  87006. this.renderList.reset();
  87007. };
  87008. BoundingBoxRenderer.prototype.render = function () {
  87009. if (this.renderList.length === 0) {
  87010. return;
  87011. }
  87012. this._prepareRessources();
  87013. if (!this._colorShader.isReady()) {
  87014. return;
  87015. }
  87016. var engine = this._scene.getEngine();
  87017. engine.setDepthWrite(false);
  87018. this._colorShader._preBind();
  87019. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87020. var boundingBox = this.renderList.data[boundingBoxIndex];
  87021. var min = boundingBox.minimum;
  87022. var max = boundingBox.maximum;
  87023. var diff = max.subtract(min);
  87024. var median = min.add(diff.scale(0.5));
  87025. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87026. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87027. .multiply(boundingBox.getWorldMatrix());
  87028. // VBOs
  87029. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87030. if (this.showBackLines) {
  87031. // Back
  87032. engine.setDepthFunctionToGreaterOrEqual();
  87033. this._scene.resetCachedMaterial();
  87034. this._colorShader.setColor4("color", this.backColor.toColor4());
  87035. this._colorShader.bind(worldMatrix);
  87036. // Draw order
  87037. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87038. }
  87039. // Front
  87040. engine.setDepthFunctionToLess();
  87041. this._scene.resetCachedMaterial();
  87042. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87043. this._colorShader.bind(worldMatrix);
  87044. // Draw order
  87045. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87046. }
  87047. this._colorShader.unbind();
  87048. engine.setDepthFunctionToLessOrEqual();
  87049. engine.setDepthWrite(true);
  87050. };
  87051. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87052. this._prepareRessources();
  87053. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87054. return;
  87055. }
  87056. var engine = this._scene.getEngine();
  87057. engine.setDepthWrite(false);
  87058. engine.setColorWrite(false);
  87059. this._colorShader._preBind();
  87060. var boundingBox = mesh._boundingInfo.boundingBox;
  87061. var min = boundingBox.minimum;
  87062. var max = boundingBox.maximum;
  87063. var diff = max.subtract(min);
  87064. var median = min.add(diff.scale(0.5));
  87065. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87066. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87067. .multiply(boundingBox.getWorldMatrix());
  87068. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87069. engine.setDepthFunctionToLess();
  87070. this._scene.resetCachedMaterial();
  87071. this._colorShader.bind(worldMatrix);
  87072. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87073. this._colorShader.unbind();
  87074. engine.setDepthFunctionToLessOrEqual();
  87075. engine.setDepthWrite(true);
  87076. engine.setColorWrite(true);
  87077. };
  87078. BoundingBoxRenderer.prototype.dispose = function () {
  87079. if (!this._colorShader) {
  87080. return;
  87081. }
  87082. this.renderList.dispose();
  87083. this._colorShader.dispose();
  87084. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87085. if (buffer) {
  87086. buffer.dispose();
  87087. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87088. }
  87089. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87090. };
  87091. return BoundingBoxRenderer;
  87092. }());
  87093. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87094. })(BABYLON || (BABYLON = {}));
  87095. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87096. var BABYLON;
  87097. (function (BABYLON) {
  87098. /**
  87099. * Renders a layer on top of an existing scene
  87100. */
  87101. var UtilityLayerRenderer = /** @class */ (function () {
  87102. /**
  87103. * Instantiates a UtilityLayerRenderer
  87104. * @param originalScene the original scene that will be rendered on top of
  87105. */
  87106. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87107. var _this = this;
  87108. this.originalScene = originalScene;
  87109. this._pointerCaptures = {};
  87110. this._lastPointerEvents = {};
  87111. /**
  87112. * If the utility layer should automatically be rendered on top of existing scene
  87113. */
  87114. this.shouldRender = true;
  87115. /**
  87116. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87117. */
  87118. this.onlyCheckPointerDownEvents = true;
  87119. /**
  87120. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87121. */
  87122. this.processAllEvents = false;
  87123. /**
  87124. * Observable raised when the pointer move from the utility layer scene to the main scene
  87125. */
  87126. this.onPointerOutObservable = new BABYLON.Observable();
  87127. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87128. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87129. originalScene.getEngine().scenes.pop();
  87130. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87131. this.utilityLayerScene.detachControl();
  87132. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87133. if (!_this.processAllEvents) {
  87134. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87135. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87136. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87137. return;
  87138. }
  87139. }
  87140. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87141. if (!prePointerInfo.ray && utilityScenePick) {
  87142. prePointerInfo.ray = utilityScenePick.ray;
  87143. }
  87144. // always fire the prepointer oversvable
  87145. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87146. // allow every non pointer down event to flow to the utility layer
  87147. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87148. if (!prePointerInfo.skipOnPointerObservable) {
  87149. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87150. }
  87151. var pointerEvent = (prePointerInfo.event);
  87152. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87153. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87154. }
  87155. return;
  87156. }
  87157. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87158. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87159. if (utilityScenePick && utilityScenePick.hit) {
  87160. if (!prePointerInfo.skipOnPointerObservable) {
  87161. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87162. }
  87163. prePointerInfo.skipOnPointerObservable = true;
  87164. }
  87165. }
  87166. else {
  87167. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87168. var pointerEvent = (prePointerInfo.event);
  87169. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87170. if (originalScenePick && utilityScenePick) {
  87171. if (utilityScenePick.distance === 0) {
  87172. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87173. _this._pointerCaptures[pointerEvent.pointerId] = true;
  87174. }
  87175. }
  87176. if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87177. if (!prePointerInfo.skipOnPointerObservable) {
  87178. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87179. _this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87180. }
  87181. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87182. }
  87183. else if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87184. // We need to send a last pointup to the utilityLayerScene to make sure animations can complete
  87185. if (_this._lastPointerEvents[pointerEvent.pointerId]) {
  87186. _this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);
  87187. delete _this._lastPointerEvents[pointerEvent.pointerId];
  87188. }
  87189. }
  87190. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87191. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87192. }
  87193. }
  87194. }
  87195. });
  87196. // Render directly on top of existing scene without clearing
  87197. this.utilityLayerScene.autoClear = false;
  87198. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87199. if (_this.shouldRender) {
  87200. _this.render();
  87201. }
  87202. });
  87203. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87204. _this.dispose();
  87205. });
  87206. this._updateCamera();
  87207. }
  87208. /**
  87209. * Renders the utility layers scene on top of the original scene
  87210. */
  87211. UtilityLayerRenderer.prototype.render = function () {
  87212. this._updateCamera();
  87213. this.utilityLayerScene.render(false);
  87214. };
  87215. /**
  87216. * Disposes of the renderer
  87217. */
  87218. UtilityLayerRenderer.prototype.dispose = function () {
  87219. this.onPointerOutObservable.clear();
  87220. if (this._afterRenderObserver) {
  87221. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87222. }
  87223. if (this._sceneDisposeObserver) {
  87224. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87225. }
  87226. if (this._originalPointerObserver) {
  87227. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87228. }
  87229. this.utilityLayerScene.dispose();
  87230. };
  87231. UtilityLayerRenderer.prototype._updateCamera = function () {
  87232. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87233. };
  87234. return UtilityLayerRenderer;
  87235. }());
  87236. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87237. })(BABYLON || (BABYLON = {}));
  87238. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87239. //# sourceMappingURL=babylon.behavior.js.map
  87240. var BABYLON;
  87241. (function (BABYLON) {
  87242. /**
  87243. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87244. */
  87245. var PointerDragBehavior = /** @class */ (function () {
  87246. /**
  87247. * Creates a pointer drag behavior that can be attached to a mesh
  87248. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  87249. */
  87250. function PointerDragBehavior(options) {
  87251. this.options = options;
  87252. this._draggingID = -1;
  87253. // Debug mode will display drag planes to help visualize behavior
  87254. this._debugMode = false;
  87255. this._maxDragAngle = Math.PI / 5;
  87256. /**
  87257. * Fires each time the attached mesh is dragged with the pointer
  87258. * * delta between last drag position and current drag position in world space
  87259. * * dragDistance along the drag axis
  87260. * * dragPlaneNormal normal of the current drag plane used during the drag
  87261. * * dragPlanePoint in world space where the drag intersects the drag plane
  87262. */
  87263. this.onDragObservable = new BABYLON.Observable();
  87264. /**
  87265. * Fires each time a drag begins (eg. mouse down on mesh)
  87266. */
  87267. this.onDragStartObservable = new BABYLON.Observable();
  87268. /**
  87269. * Fires each time a drag ends (eg. mouse release after drag)
  87270. */
  87271. this.onDragEndObservable = new BABYLON.Observable();
  87272. /**
  87273. * If the attached mesh should be moved when dragged
  87274. */
  87275. this.moveAttached = true;
  87276. /**
  87277. * Mesh with the position where the drag plane should be placed
  87278. */
  87279. this._dragPlaneParent = null;
  87280. /**
  87281. * If the drag behavior will react to drag events
  87282. */
  87283. this.enabled = true;
  87284. var optionCount = 0;
  87285. if (options === undefined) {
  87286. options = {};
  87287. }
  87288. if (options.dragAxis) {
  87289. optionCount++;
  87290. }
  87291. if (options.dragPlaneNormal) {
  87292. optionCount++;
  87293. }
  87294. if (optionCount > 1) {
  87295. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87296. }
  87297. }
  87298. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87299. /**
  87300. * The name of the behavior
  87301. */
  87302. get: function () {
  87303. return "PointerDrag";
  87304. },
  87305. enumerable: true,
  87306. configurable: true
  87307. });
  87308. /**
  87309. * Initializes the behavior
  87310. */
  87311. PointerDragBehavior.prototype.init = function () { };
  87312. /**
  87313. * Attaches the drag behavior the passed in mesh
  87314. * @param ownerNode The mesh that will be dragged around once attached
  87315. */
  87316. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87317. var _this = this;
  87318. this._scene = ownerNode.getScene();
  87319. this._attachedNode = ownerNode;
  87320. // Initialize drag plane to not interfere with existing scene
  87321. if (!PointerDragBehavior._planeScene) {
  87322. if (this._debugMode) {
  87323. PointerDragBehavior._planeScene = this._scene;
  87324. }
  87325. else {
  87326. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87327. this._scene.getEngine().scenes.pop();
  87328. }
  87329. }
  87330. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87331. // State of the drag
  87332. var dragging = false;
  87333. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  87334. var delta = new BABYLON.Vector3(0, 0, 0);
  87335. var dragLength = 0;
  87336. var pickPredicate = function (m) {
  87337. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87338. };
  87339. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87340. if (!_this.enabled) {
  87341. return;
  87342. }
  87343. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87344. if (!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87345. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87346. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87347. if (pickedPoint) {
  87348. dragging = true;
  87349. _this._draggingID = pointerInfo.event.pointerId;
  87350. lastPosition.copyFrom(pickedPoint);
  87351. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  87352. }
  87353. }
  87354. }
  87355. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87356. if (_this._draggingID == pointerInfo.event.pointerId) {
  87357. dragging = false;
  87358. _this._draggingID = -1;
  87359. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  87360. }
  87361. }
  87362. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87363. if (_this._draggingID == pointerInfo.event.pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87364. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87365. // Get angle between drag plane and ray. Only update the drag plane at non steep angles to avoid jumps in delta position
  87366. var angle = Math.acos(BABYLON.Vector3.Dot(_this._dragPlane.forward, pointerInfo.pickInfo.ray.direction));
  87367. if (angle < _this._maxDragAngle) {
  87368. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87369. }
  87370. if (pickedPoint) {
  87371. // depending on the drag mode option drag accordingly
  87372. if (_this.options.dragAxis) {
  87373. // Convert local drag axis to world
  87374. var worldDragAxis = BABYLON.Vector3.TransformCoordinates(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix());
  87375. // Project delta drag from the drag plane onto the drag axis
  87376. dragLength = BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), worldDragAxis);
  87377. worldDragAxis.scaleToRef(dragLength, delta);
  87378. }
  87379. else {
  87380. dragLength = delta.length();
  87381. pickedPoint.subtractToRef(lastPosition, delta);
  87382. }
  87383. if (_this.moveAttached) {
  87384. _this._attachedNode.position.addInPlace(delta);
  87385. }
  87386. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward });
  87387. lastPosition.copyFrom(pickedPoint);
  87388. }
  87389. }
  87390. }
  87391. });
  87392. };
  87393. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87394. var _this = this;
  87395. if (!ray) {
  87396. return null;
  87397. }
  87398. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87399. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87400. return pickResult.pickedPoint;
  87401. }
  87402. else {
  87403. return null;
  87404. }
  87405. };
  87406. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87407. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  87408. var pointA = this._dragPlaneParent ? this._dragPlaneParent.absolutePosition : this._attachedNode.absolutePosition;
  87409. if (this.options.dragAxis) {
  87410. var localAxis = BABYLON.Vector3.TransformCoordinates(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix());
  87411. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87412. var pointB = pointA.add(localAxis); // towards drag axis
  87413. var pointC = pointA.add(ray.origin.subtract(pointA).normalize()); // towards camera
  87414. // Get perpendicular line from direction to camera and drag axis
  87415. var lineA = pointB.subtract(pointA);
  87416. var lineB = pointC.subtract(pointA);
  87417. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  87418. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  87419. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  87420. this._dragPlane.position.copyFrom(pointA);
  87421. this._dragPlane.lookAt(pointA.subtract(norm));
  87422. }
  87423. else if (this.options.dragPlaneNormal) {
  87424. this._dragPlane.position.copyFrom(pointA);
  87425. this._dragPlane.lookAt(pointA.subtract(this.options.dragPlaneNormal));
  87426. }
  87427. else {
  87428. this._dragPlane.position.copyFrom(pointA);
  87429. this._dragPlane.lookAt(ray.origin);
  87430. }
  87431. this._dragPlane.computeWorldMatrix(true);
  87432. };
  87433. /**
  87434. * Detaches the behavior from the mesh
  87435. */
  87436. PointerDragBehavior.prototype.detach = function () {
  87437. if (this._pointerObserver) {
  87438. this._scene.onPointerObservable.remove(this._pointerObserver);
  87439. }
  87440. };
  87441. return PointerDragBehavior;
  87442. }());
  87443. BABYLON.PointerDragBehavior = PointerDragBehavior;
  87444. })(BABYLON || (BABYLON = {}));
  87445. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  87446. var BABYLON;
  87447. (function (BABYLON) {
  87448. /**
  87449. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  87450. */
  87451. var Gizmo = /** @class */ (function () {
  87452. /**
  87453. * Creates a gizmo
  87454. * @param gizmoLayer The utility layer the gizmo will be added to
  87455. */
  87456. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  87457. var _this = this;
  87458. this.gizmoLayer = gizmoLayer;
  87459. /**
  87460. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  87461. */
  87462. this._updateScale = true;
  87463. this._interactionsEnabled = true;
  87464. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  87465. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  87466. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  87467. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  87468. _this._rootMesh.scaling.set(dist, dist, dist);
  87469. }
  87470. if (_this.attachedMesh) {
  87471. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  87472. }
  87473. });
  87474. }
  87475. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87476. };
  87477. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  87478. get: function () {
  87479. return this._interactionsEnabled;
  87480. },
  87481. /**
  87482. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  87483. */
  87484. set: function (value) {
  87485. this._interactionsEnabled = value;
  87486. this._onInteractionsEnabledChanged(value);
  87487. },
  87488. enumerable: true,
  87489. configurable: true
  87490. });
  87491. /**
  87492. * Disposes of the gizmo
  87493. */
  87494. Gizmo.prototype.dispose = function () {
  87495. this._rootMesh.dispose();
  87496. if (this._beforeRenderObserver) {
  87497. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  87498. }
  87499. };
  87500. return Gizmo;
  87501. }());
  87502. BABYLON.Gizmo = Gizmo;
  87503. })(BABYLON || (BABYLON = {}));
  87504. //# sourceMappingURL=babylon.gizmo.js.map
  87505. var BABYLON;
  87506. (function (BABYLON) {
  87507. /**
  87508. * Single axis drag gizmo
  87509. */
  87510. var AxisDragGizmo = /** @class */ (function (_super) {
  87511. __extends(AxisDragGizmo, _super);
  87512. /**
  87513. * Creates an AxisDragGizmo
  87514. * @param gizmoLayer The utility layer the gizmo will be added to
  87515. * @param dragAxis The axis which the gizmo will be able to drag on
  87516. * @param color The color of the gizmo
  87517. */
  87518. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  87519. var _this = _super.call(this, gizmoLayer) || this;
  87520. // Create Material
  87521. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87522. coloredMaterial.disableLighting = true;
  87523. coloredMaterial.emissiveColor = color;
  87524. // Build mesh on root node
  87525. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87526. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87527. _this._rootMesh.addChild(arrowMesh);
  87528. _this._rootMesh.addChild(arrowTail);
  87529. // Position arrow pointing in its drag axis
  87530. arrowMesh.scaling.scaleInPlace(0.1);
  87531. arrowMesh.material = coloredMaterial;
  87532. arrowMesh.rotation.x = Math.PI / 2;
  87533. arrowMesh.position.z += 0.3;
  87534. arrowTail.rotation.x = Math.PI / 2;
  87535. arrowTail.material = coloredMaterial;
  87536. arrowTail.position.z += 0.2;
  87537. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87538. // Add drag behavior to handle events when the gizmo is dragged
  87539. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  87540. _this._dragBehavior.moveAttached = false;
  87541. _this._rootMesh.addBehavior(_this._dragBehavior);
  87542. _this._dragBehavior.onDragObservable.add(function (event) {
  87543. if (!_this.interactionsEnabled) {
  87544. return;
  87545. }
  87546. if (_this.attachedMesh) {
  87547. _this.attachedMesh.position.addInPlace(event.delta);
  87548. }
  87549. });
  87550. return _this;
  87551. }
  87552. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87553. this._dragBehavior.enabled = value;
  87554. };
  87555. /**
  87556. * Disposes of the gizmo
  87557. */
  87558. AxisDragGizmo.prototype.dispose = function () {
  87559. this._dragBehavior.detach();
  87560. _super.prototype.dispose.call(this);
  87561. };
  87562. return AxisDragGizmo;
  87563. }(BABYLON.Gizmo));
  87564. BABYLON.AxisDragGizmo = AxisDragGizmo;
  87565. })(BABYLON || (BABYLON = {}));
  87566. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  87567. var BABYLON;
  87568. (function (BABYLON) {
  87569. /**
  87570. * Single axis scale gizmo
  87571. */
  87572. var AxisScaleGizmo = /** @class */ (function (_super) {
  87573. __extends(AxisScaleGizmo, _super);
  87574. /**
  87575. * Creates an AxisScaleGizmo
  87576. * @param gizmoLayer The utility layer the gizmo will be added to
  87577. * @param dragAxis The axis which the gizmo will be able to scale on
  87578. * @param color The color of the gizmo
  87579. */
  87580. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  87581. var _this = _super.call(this, gizmoLayer) || this;
  87582. // Create Material
  87583. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87584. coloredMaterial.disableLighting = true;
  87585. coloredMaterial.emissiveColor = color;
  87586. // Build mesh on root node
  87587. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  87588. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87589. _this._rootMesh.addChild(arrowMesh);
  87590. _this._rootMesh.addChild(arrowTail);
  87591. // Position arrow pointing in its drag axis
  87592. arrowMesh.scaling.scaleInPlace(0.1);
  87593. arrowMesh.material = coloredMaterial;
  87594. arrowMesh.rotation.x = Math.PI / 2;
  87595. arrowMesh.position.z += 0.3;
  87596. arrowTail.rotation.x = Math.PI / 2;
  87597. arrowTail.material = coloredMaterial;
  87598. arrowTail.position.z += 0.2;
  87599. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87600. // Add drag behavior to handle events when the gizmo is dragged
  87601. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  87602. _this._dragBehavior.moveAttached = false;
  87603. _this._rootMesh.addBehavior(_this._dragBehavior);
  87604. _this._dragBehavior.onDragObservable.add(function (event) {
  87605. if (!_this.interactionsEnabled) {
  87606. return;
  87607. }
  87608. if (_this.attachedMesh) {
  87609. _this.attachedMesh.scaling.addInPlace(event.delta);
  87610. }
  87611. });
  87612. return _this;
  87613. }
  87614. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87615. this._dragBehavior.enabled = value;
  87616. };
  87617. /**
  87618. * Disposes of the gizmo
  87619. */
  87620. AxisScaleGizmo.prototype.dispose = function () {
  87621. this._dragBehavior.detach();
  87622. _super.prototype.dispose.call(this);
  87623. };
  87624. return AxisScaleGizmo;
  87625. }(BABYLON.Gizmo));
  87626. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  87627. })(BABYLON || (BABYLON = {}));
  87628. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  87629. var BABYLON;
  87630. (function (BABYLON) {
  87631. /**
  87632. * Single plane rotation gizmo
  87633. */
  87634. var PlaneRotationGizmo = /** @class */ (function (_super) {
  87635. __extends(PlaneRotationGizmo, _super);
  87636. /**
  87637. * Creates a PlaneRotationGizmo
  87638. * @param gizmoLayer The utility layer the gizmo will be added to
  87639. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  87640. * @param color The color of the gizmo
  87641. */
  87642. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  87643. var _this = _super.call(this, gizmoLayer) || this;
  87644. // Create Material
  87645. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87646. coloredMaterial.disableLighting = true;
  87647. coloredMaterial.emissiveColor = color;
  87648. // Build mesh on root node
  87649. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  87650. _this._rootMesh.addChild(rotationMesh);
  87651. // Position arrow pointing in its drag axis
  87652. rotationMesh.scaling.scaleInPlace(0.1);
  87653. rotationMesh.material = coloredMaterial;
  87654. rotationMesh.rotation.x = Math.PI / 2;
  87655. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  87656. // Add drag behavior to handle events when the gizmo is dragged
  87657. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  87658. _this._dragBehavior.moveAttached = false;
  87659. _this._rootMesh.addBehavior(_this._dragBehavior);
  87660. var lastDragPosition = null;
  87661. _this._dragBehavior.onDragStartObservable.add(function (e) {
  87662. if (!_this.interactionsEnabled) {
  87663. return;
  87664. }
  87665. lastDragPosition = e.dragPlanePoint;
  87666. });
  87667. _this._dragBehavior.onDragObservable.add(function (event) {
  87668. if (!_this.interactionsEnabled) {
  87669. return;
  87670. }
  87671. if (_this.attachedMesh && lastDragPosition) {
  87672. if (!_this.attachedMesh.rotationQuaternion) {
  87673. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  87674. }
  87675. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  87676. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  87677. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  87678. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  87679. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  87680. var angle = Math.atan2(cross.length(), dot);
  87681. var up = planeNormal.clone();
  87682. // Flip up vector depending on which side the camera is on
  87683. if (gizmoLayer.utilityLayerScene.activeCamera) {
  87684. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  87685. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  87686. up.scaleInPlace(-1);
  87687. }
  87688. }
  87689. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  87690. if (halfCircleSide)
  87691. angle = -angle;
  87692. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  87693. var quaternionCoefficient = Math.sin(angle / 2);
  87694. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  87695. // Rotate selected mesh quaternion over fixed axis
  87696. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  87697. lastDragPosition = event.dragPlanePoint;
  87698. }
  87699. });
  87700. return _this;
  87701. }
  87702. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87703. this._dragBehavior.enabled = value;
  87704. };
  87705. /**
  87706. * Disposes of the gizmo
  87707. */
  87708. PlaneRotationGizmo.prototype.dispose = function () {
  87709. this._dragBehavior.detach();
  87710. _super.prototype.dispose.call(this);
  87711. };
  87712. return PlaneRotationGizmo;
  87713. }(BABYLON.Gizmo));
  87714. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  87715. })(BABYLON || (BABYLON = {}));
  87716. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  87717. var BABYLON;
  87718. (function (BABYLON) {
  87719. /**
  87720. * Gizmo that enables dragging a mesh along 3 axis
  87721. */
  87722. var PositionGizmo = /** @class */ (function (_super) {
  87723. __extends(PositionGizmo, _super);
  87724. /**
  87725. * Creates a PositionGizmo
  87726. * @param gizmoLayer The utility layer the gizmo will be added to
  87727. */
  87728. function PositionGizmo(gizmoLayer) {
  87729. var _this = _super.call(this, gizmoLayer) || this;
  87730. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87731. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87732. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87733. return _this;
  87734. }
  87735. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  87736. set: function (mesh) {
  87737. this._xDrag.attachedMesh = mesh;
  87738. this._yDrag.attachedMesh = mesh;
  87739. this._zDrag.attachedMesh = mesh;
  87740. },
  87741. enumerable: true,
  87742. configurable: true
  87743. });
  87744. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87745. this._xDrag.interactionsEnabled = value;
  87746. this._yDrag.interactionsEnabled = value;
  87747. this._zDrag.interactionsEnabled = value;
  87748. };
  87749. /**
  87750. * Disposes of the gizmo
  87751. */
  87752. PositionGizmo.prototype.dispose = function () {
  87753. this._xDrag.dispose();
  87754. this._yDrag.dispose();
  87755. this._zDrag.dispose();
  87756. };
  87757. return PositionGizmo;
  87758. }(BABYLON.Gizmo));
  87759. BABYLON.PositionGizmo = PositionGizmo;
  87760. })(BABYLON || (BABYLON = {}));
  87761. //# sourceMappingURL=babylon.positionGizmo.js.map
  87762. var BABYLON;
  87763. (function (BABYLON) {
  87764. /**
  87765. * Gizmo that enables rotating a mesh along 3 axis
  87766. */
  87767. var RotationGizmo = /** @class */ (function (_super) {
  87768. __extends(RotationGizmo, _super);
  87769. /**
  87770. * Creates a RotationGizmo
  87771. * @param gizmoLayer The utility layer the gizmo will be added to
  87772. */
  87773. function RotationGizmo(gizmoLayer) {
  87774. var _this = _super.call(this, gizmoLayer) || this;
  87775. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87776. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87777. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87778. return _this;
  87779. }
  87780. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  87781. set: function (mesh) {
  87782. this._xDrag.attachedMesh = mesh;
  87783. this._yDrag.attachedMesh = mesh;
  87784. this._zDrag.attachedMesh = mesh;
  87785. },
  87786. enumerable: true,
  87787. configurable: true
  87788. });
  87789. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87790. this._xDrag.interactionsEnabled = value;
  87791. this._yDrag.interactionsEnabled = value;
  87792. this._zDrag.interactionsEnabled = value;
  87793. };
  87794. /**
  87795. * Disposes of the gizmo
  87796. */
  87797. RotationGizmo.prototype.dispose = function () {
  87798. this._xDrag.dispose();
  87799. this._yDrag.dispose();
  87800. this._zDrag.dispose();
  87801. };
  87802. return RotationGizmo;
  87803. }(BABYLON.Gizmo));
  87804. BABYLON.RotationGizmo = RotationGizmo;
  87805. })(BABYLON || (BABYLON = {}));
  87806. //# sourceMappingURL=babylon.rotationGizmo.js.map
  87807. var BABYLON;
  87808. (function (BABYLON) {
  87809. /**
  87810. * Gizmo that enables scaling a mesh along 3 axis
  87811. */
  87812. var ScaleGizmo = /** @class */ (function (_super) {
  87813. __extends(ScaleGizmo, _super);
  87814. /**
  87815. * Creates a ScaleGizmo
  87816. * @param gizmoLayer The utility layer the gizmo will be added to
  87817. */
  87818. function ScaleGizmo(gizmoLayer) {
  87819. var _this = _super.call(this, gizmoLayer) || this;
  87820. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87821. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87822. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87823. return _this;
  87824. }
  87825. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  87826. set: function (mesh) {
  87827. this._xDrag.attachedMesh = mesh;
  87828. this._yDrag.attachedMesh = mesh;
  87829. this._zDrag.attachedMesh = mesh;
  87830. },
  87831. enumerable: true,
  87832. configurable: true
  87833. });
  87834. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87835. this._xDrag.interactionsEnabled = value;
  87836. this._yDrag.interactionsEnabled = value;
  87837. this._zDrag.interactionsEnabled = value;
  87838. };
  87839. /**
  87840. * Disposes of the gizmo
  87841. */
  87842. ScaleGizmo.prototype.dispose = function () {
  87843. this._xDrag.dispose();
  87844. this._yDrag.dispose();
  87845. this._zDrag.dispose();
  87846. };
  87847. return ScaleGizmo;
  87848. }(BABYLON.Gizmo));
  87849. BABYLON.ScaleGizmo = ScaleGizmo;
  87850. })(BABYLON || (BABYLON = {}));
  87851. //# sourceMappingURL=babylon.scaleGizmo.js.map
  87852. var BABYLON;
  87853. (function (BABYLON) {
  87854. /**
  87855. * Bounding box gizmo
  87856. */
  87857. var BoundingBoxGizmo = /** @class */ (function (_super) {
  87858. __extends(BoundingBoxGizmo, _super);
  87859. /**
  87860. * Creates an BoundingBoxGizmo
  87861. * @param gizmoLayer The utility layer the gizmo will be added to
  87862. * @param color The color of the gizmo
  87863. */
  87864. function BoundingBoxGizmo(gizmoLayer, color) {
  87865. var _this = _super.call(this, gizmoLayer) || this;
  87866. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  87867. _this._renderObserver = null;
  87868. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  87869. _this._updateScale = false;
  87870. // Create Material
  87871. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87872. coloredMaterial.disableLighting = true;
  87873. coloredMaterial.emissiveColor = color;
  87874. // Build bounding box out of lines
  87875. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  87876. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  87877. var lines = [];
  87878. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  87879. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87880. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87881. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87882. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87883. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87884. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87885. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87886. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87887. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87888. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87889. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87890. lines.forEach(function (l) {
  87891. l.color = color;
  87892. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  87893. l.isPickable = false;
  87894. _this._lineBoundingBox.addChild(l);
  87895. });
  87896. _this._rootMesh.addChild(_this._lineBoundingBox);
  87897. // Create rotation spheres
  87898. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  87899. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  87900. var _loop_1 = function (i_1) {
  87901. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  87902. sphere.rotationQuaternion = new BABYLON.Quaternion();
  87903. sphere.material = coloredMaterial;
  87904. // Drag behavior
  87905. _dragBehavior = new BABYLON.PointerDragBehavior({});
  87906. _dragBehavior.moveAttached = false;
  87907. sphere.addBehavior(_dragBehavior);
  87908. _dragBehavior.onDragObservable.add(function (event) {
  87909. if (_this.attachedMesh) {
  87910. var worldDragDirection = sphere.forward;
  87911. // Project the world right on to the drag plane
  87912. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  87913. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  87914. // project drag delta on to the resulting drag axis and rotate based on that
  87915. var projectDist = BABYLON.Vector3.Dot(dragAxis, event.delta);
  87916. // Rotate based on axis
  87917. if (i_1 >= 8) {
  87918. _this.attachedMesh.rotation.z -= projectDist;
  87919. }
  87920. else if (i_1 >= 4) {
  87921. _this.attachedMesh.rotation.y -= projectDist;
  87922. }
  87923. else {
  87924. _this.attachedMesh.rotation.x -= projectDist;
  87925. }
  87926. }
  87927. });
  87928. // Selection/deselection
  87929. _dragBehavior.onDragStartObservable.add(function () {
  87930. _this._selectNode(sphere);
  87931. });
  87932. _dragBehavior.onDragEndObservable.add(function () {
  87933. _this._selectNode(null);
  87934. });
  87935. this_1._rotateSpheresParent.addChild(sphere);
  87936. };
  87937. var this_1 = this, _dragBehavior;
  87938. for (var i_1 = 0; i_1 < 12; i_1++) {
  87939. _loop_1(i_1);
  87940. }
  87941. _this._rootMesh.addChild(_this._rotateSpheresParent);
  87942. // Create scale cubes
  87943. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  87944. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  87945. for (var i = 0; i < 2; i++) {
  87946. for (var j = 0; j < 2; j++) {
  87947. var _loop_2 = function () {
  87948. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  87949. box.material = coloredMaterial;
  87950. // Dragging logic
  87951. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  87952. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87953. _dragBehavior.moveAttached = false;
  87954. box.addBehavior(_dragBehavior);
  87955. _dragBehavior.onDragObservable.add(function (event) {
  87956. if (_this.attachedMesh) {
  87957. // Current boudning box dimensions
  87958. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  87959. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  87960. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  87961. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  87962. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  87963. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  87964. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  87965. // Update scale and position
  87966. _this.attachedMesh.scaling.addInPlace(deltaScale);
  87967. _this.attachedMesh.position.addInPlace(worldMoveDirection);
  87968. }
  87969. });
  87970. // Selection/deselection
  87971. _dragBehavior.onDragStartObservable.add(function () {
  87972. _this._selectNode(box);
  87973. });
  87974. _dragBehavior.onDragEndObservable.add(function () {
  87975. _this._selectNode(null);
  87976. });
  87977. this_2._scaleBoxesParent.addChild(box);
  87978. };
  87979. var this_2 = this, _dragBehavior;
  87980. for (var k = 0; k < 2; k++) {
  87981. _loop_2();
  87982. }
  87983. }
  87984. }
  87985. _this._rootMesh.addChild(_this._scaleBoxesParent);
  87986. // Update bounding box positions
  87987. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  87988. _this._updateBoundingBox();
  87989. });
  87990. _this._updateBoundingBox();
  87991. return _this;
  87992. }
  87993. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  87994. this._rotateSpheresParent.getChildMeshes()
  87995. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  87996. m.isVisible = (!selectedMesh || m == selectedMesh);
  87997. });
  87998. };
  87999. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  88000. if (this.attachedMesh) {
  88001. // Update bounding dimensions/positions
  88002. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  88003. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  88004. this._boundingDimensions.copyFrom(boundBoxDimensions);
  88005. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  88006. if (!this.attachedMesh.rotationQuaternion) {
  88007. this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88008. }
  88009. this._lineBoundingBox.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  88010. this._rotateSpheresParent.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  88011. this._scaleBoxesParent.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  88012. }
  88013. // Update rotation sphere locations
  88014. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  88015. for (var i = 0; i < 3; i++) {
  88016. for (var j = 0; j < 2; j++) {
  88017. for (var k = 0; k < 2; k++) {
  88018. var index = ((i * 4) + (j * 2)) + k;
  88019. if (i == 0) {
  88020. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  88021. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88022. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88023. }
  88024. if (i == 1) {
  88025. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  88026. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88027. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88028. }
  88029. if (i == 2) {
  88030. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  88031. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88032. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88033. }
  88034. }
  88035. }
  88036. }
  88037. // Update scale box locations
  88038. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  88039. for (var i = 0; i < 2; i++) {
  88040. for (var j = 0; j < 2; j++) {
  88041. for (var k = 0; k < 2; k++) {
  88042. var index = ((i * 4) + (j * 2)) + k;
  88043. if (scaleBoxes[index]) {
  88044. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  88045. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88046. }
  88047. }
  88048. }
  88049. }
  88050. };
  88051. /**
  88052. * Disposes of the gizmo
  88053. */
  88054. BoundingBoxGizmo.prototype.dispose = function () {
  88055. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  88056. this._lineBoundingBox.dispose();
  88057. this._rotateSpheresParent.dispose();
  88058. this._scaleBoxesParent.dispose();
  88059. _super.prototype.dispose.call(this);
  88060. };
  88061. return BoundingBoxGizmo;
  88062. }(BABYLON.Gizmo));
  88063. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  88064. })(BABYLON || (BABYLON = {}));
  88065. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  88066. var BABYLON;
  88067. (function (BABYLON) {
  88068. /**
  88069. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  88070. */
  88071. var GizmoManager = /** @class */ (function () {
  88072. /**
  88073. * Instatiates a gizmo manager
  88074. * @param scene the scene to overlay the gizmos on top of
  88075. * @param options If only a single gizmo should exist at one time
  88076. */
  88077. function GizmoManager(scene, options) {
  88078. var _this = this;
  88079. this.scene = scene;
  88080. // Set of gizmos that are currently in the scene for each mesh
  88081. this._gizmoSet = {};
  88082. this._pointerObserver = null;
  88083. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  88084. // Options parsing
  88085. if (!options) {
  88086. options = {};
  88087. }
  88088. if (options.singleGizmo === undefined) {
  88089. options.singleGizmo = true;
  88090. }
  88091. // Instatiate/dispose gizmos based on pointer actions
  88092. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  88093. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88094. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  88095. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  88096. if (options.singleGizmo) {
  88097. _this._clearGizmos();
  88098. }
  88099. // Enable gizmo when mesh is selected
  88100. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  88101. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88102. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88103. }
  88104. else {
  88105. if (!options.singleGizmo) {
  88106. // Disable gizmo when clicked again
  88107. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  88108. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  88109. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  88110. }
  88111. }
  88112. }
  88113. else {
  88114. if (options.singleGizmo) {
  88115. // Disable gizmo when clicked away
  88116. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88117. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  88118. if (gizmoPick && !gizmoPick.hit) {
  88119. _this._clearGizmos();
  88120. }
  88121. }
  88122. }
  88123. }
  88124. }
  88125. });
  88126. }
  88127. /**
  88128. * Disposes of the gizmo manager
  88129. */
  88130. GizmoManager.prototype.dispose = function () {
  88131. this.scene.onPointerObservable.remove(this._pointerObserver);
  88132. this._clearGizmos();
  88133. this._gizmoLayer.dispose();
  88134. };
  88135. GizmoManager.prototype._clearGizmos = function () {
  88136. for (var key in this._gizmoSet) {
  88137. if (this._gizmoSet.hasOwnProperty(key)) {
  88138. this._gizmoSet[key].positionGizmo.dispose();
  88139. this._gizmoSet[key].rotationGizmo.dispose();
  88140. delete this._gizmoSet[key];
  88141. }
  88142. }
  88143. };
  88144. return GizmoManager;
  88145. }());
  88146. BABYLON.GizmoManager = GizmoManager;
  88147. })(BABYLON || (BABYLON = {}));
  88148. //# sourceMappingURL=babylon.gizmoManager.js.map
  88149. var BABYLON;
  88150. (function (BABYLON) {
  88151. /**
  88152. * Defines a target to use with MorphTargetManager
  88153. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88154. */
  88155. var MorphTarget = /** @class */ (function () {
  88156. /**
  88157. * Creates a new MorphTarget
  88158. * @param name defines the name of the target
  88159. * @param influence defines the influence to use
  88160. */
  88161. function MorphTarget(
  88162. /** defines the name of the target */
  88163. name, influence, scene) {
  88164. if (influence === void 0) { influence = 0; }
  88165. if (scene === void 0) { scene = null; }
  88166. this.name = name;
  88167. /**
  88168. * Gets or sets the list of animations
  88169. */
  88170. this.animations = new Array();
  88171. this._positions = null;
  88172. this._normals = null;
  88173. this._tangents = null;
  88174. /**
  88175. * Observable raised when the influence changes
  88176. */
  88177. this.onInfluenceChanged = new BABYLON.Observable();
  88178. this._animationPropertiesOverride = null;
  88179. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88180. this.influence = influence;
  88181. }
  88182. Object.defineProperty(MorphTarget.prototype, "influence", {
  88183. /**
  88184. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  88185. */
  88186. get: function () {
  88187. return this._influence;
  88188. },
  88189. set: function (influence) {
  88190. if (this._influence === influence) {
  88191. return;
  88192. }
  88193. var previous = this._influence;
  88194. this._influence = influence;
  88195. if (this.onInfluenceChanged.hasObservers) {
  88196. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  88197. }
  88198. },
  88199. enumerable: true,
  88200. configurable: true
  88201. });
  88202. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  88203. /**
  88204. * Gets or sets the animation properties override
  88205. */
  88206. get: function () {
  88207. if (!this._animationPropertiesOverride && this._scene) {
  88208. return this._scene.animationPropertiesOverride;
  88209. }
  88210. return this._animationPropertiesOverride;
  88211. },
  88212. set: function (value) {
  88213. this._animationPropertiesOverride = value;
  88214. },
  88215. enumerable: true,
  88216. configurable: true
  88217. });
  88218. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  88219. /**
  88220. * Gets a boolean defining if the target contains position data
  88221. */
  88222. get: function () {
  88223. return !!this._positions;
  88224. },
  88225. enumerable: true,
  88226. configurable: true
  88227. });
  88228. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  88229. /**
  88230. * Gets a boolean defining if the target contains normal data
  88231. */
  88232. get: function () {
  88233. return !!this._normals;
  88234. },
  88235. enumerable: true,
  88236. configurable: true
  88237. });
  88238. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  88239. /**
  88240. * Gets a boolean defining if the target contains tangent data
  88241. */
  88242. get: function () {
  88243. return !!this._tangents;
  88244. },
  88245. enumerable: true,
  88246. configurable: true
  88247. });
  88248. /**
  88249. * Affects position data to this target
  88250. * @param data defines the position data to use
  88251. */
  88252. MorphTarget.prototype.setPositions = function (data) {
  88253. this._positions = data;
  88254. };
  88255. /**
  88256. * Gets the position data stored in this target
  88257. * @returns a FloatArray containing the position data (or null if not present)
  88258. */
  88259. MorphTarget.prototype.getPositions = function () {
  88260. return this._positions;
  88261. };
  88262. /**
  88263. * Affects normal data to this target
  88264. * @param data defines the normal data to use
  88265. */
  88266. MorphTarget.prototype.setNormals = function (data) {
  88267. this._normals = data;
  88268. };
  88269. /**
  88270. * Gets the normal data stored in this target
  88271. * @returns a FloatArray containing the normal data (or null if not present)
  88272. */
  88273. MorphTarget.prototype.getNormals = function () {
  88274. return this._normals;
  88275. };
  88276. /**
  88277. * Affects tangent data to this target
  88278. * @param data defines the tangent data to use
  88279. */
  88280. MorphTarget.prototype.setTangents = function (data) {
  88281. this._tangents = data;
  88282. };
  88283. /**
  88284. * Gets the tangent data stored in this target
  88285. * @returns a FloatArray containing the tangent data (or null if not present)
  88286. */
  88287. MorphTarget.prototype.getTangents = function () {
  88288. return this._tangents;
  88289. };
  88290. /**
  88291. * Serializes the current target into a Serialization object
  88292. * @returns the serialized object
  88293. */
  88294. MorphTarget.prototype.serialize = function () {
  88295. var serializationObject = {};
  88296. serializationObject.name = this.name;
  88297. serializationObject.influence = this.influence;
  88298. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  88299. if (this.hasNormals) {
  88300. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  88301. }
  88302. if (this.hasTangents) {
  88303. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  88304. }
  88305. // Animations
  88306. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  88307. return serializationObject;
  88308. };
  88309. // Statics
  88310. /**
  88311. * Creates a new target from serialized data
  88312. * @param serializationObject defines the serialized data to use
  88313. * @returns a new MorphTarget
  88314. */
  88315. MorphTarget.Parse = function (serializationObject) {
  88316. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  88317. result.setPositions(serializationObject.positions);
  88318. if (serializationObject.normals) {
  88319. result.setNormals(serializationObject.normals);
  88320. }
  88321. if (serializationObject.tangents) {
  88322. result.setTangents(serializationObject.tangents);
  88323. }
  88324. // Animations
  88325. if (serializationObject.animations) {
  88326. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  88327. var parsedAnimation = serializationObject.animations[animationIndex];
  88328. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  88329. }
  88330. }
  88331. return result;
  88332. };
  88333. /**
  88334. * Creates a MorphTarget from mesh data
  88335. * @param mesh defines the source mesh
  88336. * @param name defines the name to use for the new target
  88337. * @param influence defines the influence to attach to the target
  88338. * @returns a new MorphTarget
  88339. */
  88340. MorphTarget.FromMesh = function (mesh, name, influence) {
  88341. if (!name) {
  88342. name = mesh.name;
  88343. }
  88344. var result = new MorphTarget(name, influence, mesh.getScene());
  88345. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88346. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88347. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  88348. }
  88349. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  88350. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  88351. }
  88352. return result;
  88353. };
  88354. return MorphTarget;
  88355. }());
  88356. BABYLON.MorphTarget = MorphTarget;
  88357. })(BABYLON || (BABYLON = {}));
  88358. //# sourceMappingURL=babylon.morphTarget.js.map
  88359. var BABYLON;
  88360. (function (BABYLON) {
  88361. /**
  88362. * This class is used to deform meshes using morphing between different targets
  88363. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88364. */
  88365. var MorphTargetManager = /** @class */ (function () {
  88366. /**
  88367. * Creates a new MorphTargetManager
  88368. * @param scene defines the current scene
  88369. */
  88370. function MorphTargetManager(scene) {
  88371. if (scene === void 0) { scene = null; }
  88372. this._targets = new Array();
  88373. this._targetObservable = new Array();
  88374. this._activeTargets = new BABYLON.SmartArray(16);
  88375. this._supportsNormals = false;
  88376. this._supportsTangents = false;
  88377. this._vertexCount = 0;
  88378. this._uniqueId = 0;
  88379. this._tempInfluences = new Array();
  88380. if (!scene) {
  88381. scene = BABYLON.Engine.LastCreatedScene;
  88382. }
  88383. this._scene = scene;
  88384. if (this._scene) {
  88385. this._scene.morphTargetManagers.push(this);
  88386. this._uniqueId = this._scene.getUniqueId();
  88387. }
  88388. }
  88389. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  88390. /**
  88391. * Gets the unique ID of this manager
  88392. */
  88393. get: function () {
  88394. return this._uniqueId;
  88395. },
  88396. enumerable: true,
  88397. configurable: true
  88398. });
  88399. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  88400. /**
  88401. * Gets the number of vertices handled by this manager
  88402. */
  88403. get: function () {
  88404. return this._vertexCount;
  88405. },
  88406. enumerable: true,
  88407. configurable: true
  88408. });
  88409. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  88410. /**
  88411. * Gets a boolean indicating if this manager supports morphing of normals
  88412. */
  88413. get: function () {
  88414. return this._supportsNormals;
  88415. },
  88416. enumerable: true,
  88417. configurable: true
  88418. });
  88419. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  88420. /**
  88421. * Gets a boolean indicating if this manager supports morphing of tangents
  88422. */
  88423. get: function () {
  88424. return this._supportsTangents;
  88425. },
  88426. enumerable: true,
  88427. configurable: true
  88428. });
  88429. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  88430. /**
  88431. * Gets the number of targets stored in this manager
  88432. */
  88433. get: function () {
  88434. return this._targets.length;
  88435. },
  88436. enumerable: true,
  88437. configurable: true
  88438. });
  88439. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  88440. /**
  88441. * Gets the number of influencers (ie. the number of targets with influences > 0)
  88442. */
  88443. get: function () {
  88444. return this._activeTargets.length;
  88445. },
  88446. enumerable: true,
  88447. configurable: true
  88448. });
  88449. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  88450. /**
  88451. * Gets the list of influences (one per target)
  88452. */
  88453. get: function () {
  88454. return this._influences;
  88455. },
  88456. enumerable: true,
  88457. configurable: true
  88458. });
  88459. /**
  88460. * Gets the active target at specified index. An active target is a target with an influence > 0
  88461. * @param index defines the index to check
  88462. * @returns the requested target
  88463. */
  88464. MorphTargetManager.prototype.getActiveTarget = function (index) {
  88465. return this._activeTargets.data[index];
  88466. };
  88467. /**
  88468. * Gets the target at specified index
  88469. * @param index defines the index to check
  88470. * @returns the requested target
  88471. */
  88472. MorphTargetManager.prototype.getTarget = function (index) {
  88473. return this._targets[index];
  88474. };
  88475. /**
  88476. * Add a new target to this manager
  88477. * @param target defines the target to add
  88478. */
  88479. MorphTargetManager.prototype.addTarget = function (target) {
  88480. var _this = this;
  88481. this._targets.push(target);
  88482. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  88483. _this._syncActiveTargets(needUpdate);
  88484. }));
  88485. this._syncActiveTargets(true);
  88486. };
  88487. /**
  88488. * Removes a target from the manager
  88489. * @param target defines the target to remove
  88490. */
  88491. MorphTargetManager.prototype.removeTarget = function (target) {
  88492. var index = this._targets.indexOf(target);
  88493. if (index >= 0) {
  88494. this._targets.splice(index, 1);
  88495. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  88496. this._syncActiveTargets(true);
  88497. }
  88498. };
  88499. /**
  88500. * Serializes the current manager into a Serialization object
  88501. * @returns the serialized object
  88502. */
  88503. MorphTargetManager.prototype.serialize = function () {
  88504. var serializationObject = {};
  88505. serializationObject.id = this.uniqueId;
  88506. serializationObject.targets = [];
  88507. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88508. var target = _a[_i];
  88509. serializationObject.targets.push(target.serialize());
  88510. }
  88511. return serializationObject;
  88512. };
  88513. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  88514. var influenceCount = 0;
  88515. this._activeTargets.reset();
  88516. this._supportsNormals = true;
  88517. this._supportsTangents = true;
  88518. this._vertexCount = 0;
  88519. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88520. var target = _a[_i];
  88521. this._activeTargets.push(target);
  88522. this._tempInfluences[influenceCount++] = target.influence;
  88523. var positions = target.getPositions();
  88524. if (positions) {
  88525. this._supportsNormals = this._supportsNormals && target.hasNormals;
  88526. this._supportsTangents = this._supportsTangents && target.hasTangents;
  88527. var vertexCount = positions.length / 3;
  88528. if (this._vertexCount === 0) {
  88529. this._vertexCount = vertexCount;
  88530. }
  88531. else if (this._vertexCount !== vertexCount) {
  88532. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  88533. return;
  88534. }
  88535. }
  88536. }
  88537. if (!this._influences || this._influences.length !== influenceCount) {
  88538. this._influences = new Float32Array(influenceCount);
  88539. }
  88540. for (var index = 0; index < influenceCount; index++) {
  88541. this._influences[index] = this._tempInfluences[index];
  88542. }
  88543. if (needUpdate) {
  88544. this.synchronize();
  88545. }
  88546. };
  88547. /**
  88548. * Syncrhonize the targets with all the meshes using this morph target manager
  88549. */
  88550. MorphTargetManager.prototype.synchronize = function () {
  88551. if (!this._scene) {
  88552. return;
  88553. }
  88554. // Flag meshes as dirty to resync with the active targets
  88555. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  88556. var mesh = _a[_i];
  88557. if (mesh.morphTargetManager === this) {
  88558. mesh._syncGeometryWithMorphTargetManager();
  88559. }
  88560. }
  88561. };
  88562. // Statics
  88563. /**
  88564. * Creates a new MorphTargetManager from serialized data
  88565. * @param serializationObject defines the serialized data
  88566. * @param scene defines the hosting scene
  88567. * @returns the new MorphTargetManager
  88568. */
  88569. MorphTargetManager.Parse = function (serializationObject, scene) {
  88570. var result = new MorphTargetManager(scene);
  88571. result._uniqueId = serializationObject.id;
  88572. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  88573. var targetData = _a[_i];
  88574. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  88575. }
  88576. return result;
  88577. };
  88578. return MorphTargetManager;
  88579. }());
  88580. BABYLON.MorphTargetManager = MorphTargetManager;
  88581. })(BABYLON || (BABYLON = {}));
  88582. //# sourceMappingURL=babylon.morphTargetManager.js.map
  88583. var BABYLON;
  88584. (function (BABYLON) {
  88585. var Octree = /** @class */ (function () {
  88586. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  88587. if (maxDepth === void 0) { maxDepth = 2; }
  88588. this.maxDepth = maxDepth;
  88589. this.dynamicContent = new Array();
  88590. this._maxBlockCapacity = maxBlockCapacity || 64;
  88591. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  88592. this._creationFunc = creationFunc;
  88593. }
  88594. // Methods
  88595. Octree.prototype.update = function (worldMin, worldMax, entries) {
  88596. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  88597. };
  88598. Octree.prototype.addMesh = function (entry) {
  88599. for (var index = 0; index < this.blocks.length; index++) {
  88600. var block = this.blocks[index];
  88601. block.addEntry(entry);
  88602. }
  88603. };
  88604. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  88605. this._selectionContent.reset();
  88606. for (var index = 0; index < this.blocks.length; index++) {
  88607. var block = this.blocks[index];
  88608. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  88609. }
  88610. if (allowDuplicate) {
  88611. this._selectionContent.concat(this.dynamicContent);
  88612. }
  88613. else {
  88614. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88615. }
  88616. return this._selectionContent;
  88617. };
  88618. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  88619. this._selectionContent.reset();
  88620. for (var index = 0; index < this.blocks.length; index++) {
  88621. var block = this.blocks[index];
  88622. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  88623. }
  88624. if (allowDuplicate) {
  88625. this._selectionContent.concat(this.dynamicContent);
  88626. }
  88627. else {
  88628. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88629. }
  88630. return this._selectionContent;
  88631. };
  88632. Octree.prototype.intersectsRay = function (ray) {
  88633. this._selectionContent.reset();
  88634. for (var index = 0; index < this.blocks.length; index++) {
  88635. var block = this.blocks[index];
  88636. block.intersectsRay(ray, this._selectionContent);
  88637. }
  88638. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88639. return this._selectionContent;
  88640. };
  88641. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  88642. target.blocks = new Array();
  88643. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  88644. // Segmenting space
  88645. for (var x = 0; x < 2; x++) {
  88646. for (var y = 0; y < 2; y++) {
  88647. for (var z = 0; z < 2; z++) {
  88648. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  88649. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  88650. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  88651. block.addEntries(entries);
  88652. target.blocks.push(block);
  88653. }
  88654. }
  88655. }
  88656. };
  88657. Octree.CreationFuncForMeshes = function (entry, block) {
  88658. var boundingInfo = entry.getBoundingInfo();
  88659. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88660. block.entries.push(entry);
  88661. }
  88662. };
  88663. Octree.CreationFuncForSubMeshes = function (entry, block) {
  88664. var boundingInfo = entry.getBoundingInfo();
  88665. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88666. block.entries.push(entry);
  88667. }
  88668. };
  88669. return Octree;
  88670. }());
  88671. BABYLON.Octree = Octree;
  88672. })(BABYLON || (BABYLON = {}));
  88673. //# sourceMappingURL=babylon.octree.js.map
  88674. var BABYLON;
  88675. (function (BABYLON) {
  88676. var OctreeBlock = /** @class */ (function () {
  88677. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  88678. this.entries = new Array();
  88679. this._boundingVectors = new Array();
  88680. this._capacity = capacity;
  88681. this._depth = depth;
  88682. this._maxDepth = maxDepth;
  88683. this._creationFunc = creationFunc;
  88684. this._minPoint = minPoint;
  88685. this._maxPoint = maxPoint;
  88686. this._boundingVectors.push(minPoint.clone());
  88687. this._boundingVectors.push(maxPoint.clone());
  88688. this._boundingVectors.push(minPoint.clone());
  88689. this._boundingVectors[2].x = maxPoint.x;
  88690. this._boundingVectors.push(minPoint.clone());
  88691. this._boundingVectors[3].y = maxPoint.y;
  88692. this._boundingVectors.push(minPoint.clone());
  88693. this._boundingVectors[4].z = maxPoint.z;
  88694. this._boundingVectors.push(maxPoint.clone());
  88695. this._boundingVectors[5].z = minPoint.z;
  88696. this._boundingVectors.push(maxPoint.clone());
  88697. this._boundingVectors[6].x = minPoint.x;
  88698. this._boundingVectors.push(maxPoint.clone());
  88699. this._boundingVectors[7].y = minPoint.y;
  88700. }
  88701. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  88702. // Property
  88703. get: function () {
  88704. return this._capacity;
  88705. },
  88706. enumerable: true,
  88707. configurable: true
  88708. });
  88709. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  88710. get: function () {
  88711. return this._minPoint;
  88712. },
  88713. enumerable: true,
  88714. configurable: true
  88715. });
  88716. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  88717. get: function () {
  88718. return this._maxPoint;
  88719. },
  88720. enumerable: true,
  88721. configurable: true
  88722. });
  88723. // Methods
  88724. OctreeBlock.prototype.addEntry = function (entry) {
  88725. if (this.blocks) {
  88726. for (var index = 0; index < this.blocks.length; index++) {
  88727. var block = this.blocks[index];
  88728. block.addEntry(entry);
  88729. }
  88730. return;
  88731. }
  88732. this._creationFunc(entry, this);
  88733. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  88734. this.createInnerBlocks();
  88735. }
  88736. };
  88737. OctreeBlock.prototype.addEntries = function (entries) {
  88738. for (var index = 0; index < entries.length; index++) {
  88739. var mesh = entries[index];
  88740. this.addEntry(mesh);
  88741. }
  88742. };
  88743. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  88744. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  88745. if (this.blocks) {
  88746. for (var index = 0; index < this.blocks.length; index++) {
  88747. var block = this.blocks[index];
  88748. block.select(frustumPlanes, selection, allowDuplicate);
  88749. }
  88750. return;
  88751. }
  88752. if (allowDuplicate) {
  88753. selection.concat(this.entries);
  88754. }
  88755. else {
  88756. selection.concatWithNoDuplicate(this.entries);
  88757. }
  88758. }
  88759. };
  88760. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  88761. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  88762. if (this.blocks) {
  88763. for (var index = 0; index < this.blocks.length; index++) {
  88764. var block = this.blocks[index];
  88765. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  88766. }
  88767. return;
  88768. }
  88769. if (allowDuplicate) {
  88770. selection.concat(this.entries);
  88771. }
  88772. else {
  88773. selection.concatWithNoDuplicate(this.entries);
  88774. }
  88775. }
  88776. };
  88777. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  88778. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  88779. if (this.blocks) {
  88780. for (var index = 0; index < this.blocks.length; index++) {
  88781. var block = this.blocks[index];
  88782. block.intersectsRay(ray, selection);
  88783. }
  88784. return;
  88785. }
  88786. selection.concatWithNoDuplicate(this.entries);
  88787. }
  88788. };
  88789. OctreeBlock.prototype.createInnerBlocks = function () {
  88790. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  88791. };
  88792. return OctreeBlock;
  88793. }());
  88794. BABYLON.OctreeBlock = OctreeBlock;
  88795. })(BABYLON || (BABYLON = {}));
  88796. //# sourceMappingURL=babylon.octreeBlock.js.map
  88797. var BABYLON;
  88798. (function (BABYLON) {
  88799. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  88800. __extends(VRDistortionCorrectionPostProcess, _super);
  88801. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  88802. var _this = _super.call(this, name, "vrDistortionCorrection", [
  88803. 'LensCenter',
  88804. 'Scale',
  88805. 'ScaleIn',
  88806. 'HmdWarpParam'
  88807. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  88808. _this._isRightEye = isRightEye;
  88809. _this._distortionFactors = vrMetrics.distortionK;
  88810. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  88811. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  88812. _this.adaptScaleToCurrentViewport = true;
  88813. _this.onSizeChangedObservable.add(function () {
  88814. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  88815. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  88816. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  88817. });
  88818. _this.onApplyObservable.add(function (effect) {
  88819. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  88820. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  88821. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  88822. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  88823. });
  88824. return _this;
  88825. }
  88826. return VRDistortionCorrectionPostProcess;
  88827. }(BABYLON.PostProcess));
  88828. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  88829. })(BABYLON || (BABYLON = {}));
  88830. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  88831. var BABYLON;
  88832. (function (BABYLON) {
  88833. /**
  88834. * Postprocess used to generate anaglyphic rendering
  88835. */
  88836. var AnaglyphPostProcess = /** @class */ (function (_super) {
  88837. __extends(AnaglyphPostProcess, _super);
  88838. /**
  88839. * Creates a new AnaglyphPostProcess
  88840. * @param name defines postprocess name
  88841. * @param options defines creation options or target ratio scale
  88842. * @param rigCameras defines cameras using this postprocess
  88843. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  88844. * @param engine defines hosting engine
  88845. * @param reusable defines if the postprocess will be reused multiple times per frame
  88846. */
  88847. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  88848. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  88849. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88850. _this.onApplyObservable.add(function (effect) {
  88851. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  88852. });
  88853. return _this;
  88854. }
  88855. return AnaglyphPostProcess;
  88856. }(BABYLON.PostProcess));
  88857. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  88858. })(BABYLON || (BABYLON = {}));
  88859. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  88860. var BABYLON;
  88861. (function (BABYLON) {
  88862. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  88863. __extends(StereoscopicInterlacePostProcess, _super);
  88864. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  88865. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  88866. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88867. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88868. _this.onSizeChangedObservable.add(function () {
  88869. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88870. });
  88871. _this.onApplyObservable.add(function (effect) {
  88872. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  88873. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  88874. });
  88875. return _this;
  88876. }
  88877. return StereoscopicInterlacePostProcess;
  88878. }(BABYLON.PostProcess));
  88879. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  88880. })(BABYLON || (BABYLON = {}));
  88881. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  88882. var BABYLON;
  88883. (function (BABYLON) {
  88884. /**
  88885. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  88886. * Screen rotation is taken into account.
  88887. */
  88888. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  88889. function FreeCameraDeviceOrientationInput() {
  88890. var _this = this;
  88891. this._screenOrientationAngle = 0;
  88892. this._screenQuaternion = new BABYLON.Quaternion();
  88893. this._alpha = 0;
  88894. this._beta = 0;
  88895. this._gamma = 0;
  88896. this._orientationChanged = function () {
  88897. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  88898. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  88899. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  88900. };
  88901. this._deviceOrientation = function (evt) {
  88902. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  88903. _this._beta = evt.beta !== null ? evt.beta : 0;
  88904. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  88905. };
  88906. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  88907. this._orientationChanged();
  88908. }
  88909. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  88910. get: function () {
  88911. return this._camera;
  88912. },
  88913. set: function (camera) {
  88914. this._camera = camera;
  88915. if (this._camera != null && !this._camera.rotationQuaternion) {
  88916. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  88917. }
  88918. },
  88919. enumerable: true,
  88920. configurable: true
  88921. });
  88922. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88923. window.addEventListener("orientationchange", this._orientationChanged);
  88924. window.addEventListener("deviceorientation", this._deviceOrientation);
  88925. //In certain cases, the attach control is called AFTER orientation was changed,
  88926. //So this is needed.
  88927. this._orientationChanged();
  88928. };
  88929. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  88930. window.removeEventListener("orientationchange", this._orientationChanged);
  88931. window.removeEventListener("deviceorientation", this._deviceOrientation);
  88932. };
  88933. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  88934. //if no device orientation provided, don't update the rotation.
  88935. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  88936. if (!this._alpha)
  88937. return;
  88938. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  88939. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  88940. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  88941. //Mirror on XY Plane
  88942. this._camera.rotationQuaternion.z *= -1;
  88943. this._camera.rotationQuaternion.w *= -1;
  88944. };
  88945. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  88946. return "FreeCameraDeviceOrientationInput";
  88947. };
  88948. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  88949. return "deviceOrientation";
  88950. };
  88951. return FreeCameraDeviceOrientationInput;
  88952. }());
  88953. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  88954. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  88955. })(BABYLON || (BABYLON = {}));
  88956. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  88957. var BABYLON;
  88958. (function (BABYLON) {
  88959. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  88960. function ArcRotateCameraVRDeviceOrientationInput() {
  88961. this.alphaCorrection = 1;
  88962. this.betaCorrection = 1;
  88963. this.gammaCorrection = 1;
  88964. this._alpha = 0;
  88965. this._gamma = 0;
  88966. this._dirty = false;
  88967. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  88968. }
  88969. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88970. this.camera.attachControl(element, noPreventDefault);
  88971. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  88972. };
  88973. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  88974. if (evt.alpha !== null) {
  88975. this._alpha = +evt.alpha | 0;
  88976. }
  88977. if (evt.gamma !== null) {
  88978. this._gamma = +evt.gamma | 0;
  88979. }
  88980. this._dirty = true;
  88981. };
  88982. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  88983. if (this._dirty) {
  88984. this._dirty = false;
  88985. if (this._gamma < 0) {
  88986. this._gamma = 180 + this._gamma;
  88987. }
  88988. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  88989. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  88990. }
  88991. };
  88992. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  88993. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  88994. };
  88995. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  88996. return "ArcRotateCameraVRDeviceOrientationInput";
  88997. };
  88998. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  88999. return "VRDeviceOrientation";
  89000. };
  89001. return ArcRotateCameraVRDeviceOrientationInput;
  89002. }());
  89003. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  89004. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  89005. })(BABYLON || (BABYLON = {}));
  89006. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  89007. var BABYLON;
  89008. (function (BABYLON) {
  89009. var VRCameraMetrics = /** @class */ (function () {
  89010. function VRCameraMetrics() {
  89011. this.compensateDistortion = true;
  89012. }
  89013. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  89014. get: function () {
  89015. return this.hResolution / (2 * this.vResolution);
  89016. },
  89017. enumerable: true,
  89018. configurable: true
  89019. });
  89020. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  89021. get: function () {
  89022. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  89023. },
  89024. enumerable: true,
  89025. configurable: true
  89026. });
  89027. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  89028. get: function () {
  89029. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89030. var h = (4 * meters) / this.hScreenSize;
  89031. return BABYLON.Matrix.Translation(h, 0, 0);
  89032. },
  89033. enumerable: true,
  89034. configurable: true
  89035. });
  89036. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  89037. get: function () {
  89038. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89039. var h = (4 * meters) / this.hScreenSize;
  89040. return BABYLON.Matrix.Translation(-h, 0, 0);
  89041. },
  89042. enumerable: true,
  89043. configurable: true
  89044. });
  89045. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  89046. get: function () {
  89047. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  89048. },
  89049. enumerable: true,
  89050. configurable: true
  89051. });
  89052. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  89053. get: function () {
  89054. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  89055. },
  89056. enumerable: true,
  89057. configurable: true
  89058. });
  89059. VRCameraMetrics.GetDefault = function () {
  89060. var result = new VRCameraMetrics();
  89061. result.hResolution = 1280;
  89062. result.vResolution = 800;
  89063. result.hScreenSize = 0.149759993;
  89064. result.vScreenSize = 0.0935999975;
  89065. result.vScreenCenter = 0.0467999987;
  89066. result.eyeToScreenDistance = 0.0410000011;
  89067. result.lensSeparationDistance = 0.0635000020;
  89068. result.interpupillaryDistance = 0.0640000030;
  89069. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  89070. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  89071. result.postProcessScaleFactor = 1.714605507808412;
  89072. result.lensCenterOffset = 0.151976421;
  89073. return result;
  89074. };
  89075. return VRCameraMetrics;
  89076. }());
  89077. BABYLON.VRCameraMetrics = VRCameraMetrics;
  89078. })(BABYLON || (BABYLON = {}));
  89079. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  89080. var BABYLON;
  89081. (function (BABYLON) {
  89082. /**
  89083. * This represents a WebVR camera.
  89084. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  89085. * @example http://doc.babylonjs.com/how_to/webvr_camera
  89086. */
  89087. var WebVRFreeCamera = /** @class */ (function (_super) {
  89088. __extends(WebVRFreeCamera, _super);
  89089. /**
  89090. * Instantiates a WebVRFreeCamera.
  89091. * @param name The name of the WebVRFreeCamera
  89092. * @param position The starting anchor position for the camera
  89093. * @param scene The scene the camera belongs to
  89094. * @param webVROptions a set of customizable options for the webVRCamera
  89095. */
  89096. function WebVRFreeCamera(name, position, scene, webVROptions) {
  89097. if (webVROptions === void 0) { webVROptions = {}; }
  89098. var _this = _super.call(this, name, position, scene) || this;
  89099. _this.webVROptions = webVROptions;
  89100. /**
  89101. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  89102. */
  89103. _this._vrDevice = null;
  89104. /**
  89105. * The rawPose of the vrDevice.
  89106. */
  89107. _this.rawPose = null;
  89108. _this._specsVersion = "1.1";
  89109. _this._attached = false;
  89110. _this._descendants = [];
  89111. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  89112. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  89113. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  89114. _this._standingMatrix = null;
  89115. /**
  89116. * Represents device position in babylon space.
  89117. */
  89118. _this.devicePosition = BABYLON.Vector3.Zero();
  89119. /**
  89120. * Represents device rotation in babylon space.
  89121. */
  89122. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  89123. /**
  89124. * The scale of the device to be used when translating from device space to babylon space.
  89125. */
  89126. _this.deviceScaleFactor = 1;
  89127. _this._deviceToWorld = BABYLON.Matrix.Identity();
  89128. _this._worldToDevice = BABYLON.Matrix.Identity();
  89129. /**
  89130. * References to the webVR controllers for the vrDevice.
  89131. */
  89132. _this.controllers = [];
  89133. /**
  89134. * Emits an event when a controller is attached.
  89135. */
  89136. _this.onControllersAttachedObservable = new BABYLON.Observable();
  89137. /**
  89138. * Emits an event when a controller's mesh has been loaded;
  89139. */
  89140. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89141. /**
  89142. * If the rig cameras be used as parent instead of this camera.
  89143. */
  89144. _this.rigParenting = true;
  89145. _this._defaultHeight = undefined;
  89146. _this._workingVector = BABYLON.Vector3.Zero();
  89147. _this._oneVector = BABYLON.Vector3.One();
  89148. _this._workingMatrix = BABYLON.Matrix.Identity();
  89149. _this._cache.position = BABYLON.Vector3.Zero();
  89150. if (webVROptions.defaultHeight) {
  89151. _this._defaultHeight = webVROptions.defaultHeight;
  89152. _this.position.y = _this._defaultHeight;
  89153. }
  89154. _this.minZ = 0.1;
  89155. //legacy support - the compensation boolean was removed.
  89156. if (arguments.length === 5) {
  89157. _this.webVROptions = arguments[4];
  89158. }
  89159. // default webVR options
  89160. if (_this.webVROptions.trackPosition == undefined) {
  89161. _this.webVROptions.trackPosition = true;
  89162. }
  89163. if (_this.webVROptions.controllerMeshes == undefined) {
  89164. _this.webVROptions.controllerMeshes = true;
  89165. }
  89166. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  89167. _this.webVROptions.defaultLightingOnControllers = true;
  89168. }
  89169. _this.rotationQuaternion = new BABYLON.Quaternion();
  89170. if (_this.webVROptions && _this.webVROptions.positionScale) {
  89171. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  89172. }
  89173. //enable VR
  89174. var engine = _this.getEngine();
  89175. _this._onVREnabled = function (success) { if (success) {
  89176. _this.initControllers();
  89177. } };
  89178. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  89179. engine.initWebVR().add(function (event) {
  89180. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  89181. return;
  89182. }
  89183. _this._vrDevice = event.vrDisplay;
  89184. //reset the rig parameters.
  89185. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  89186. if (_this._attached) {
  89187. _this.getEngine().enableVR();
  89188. }
  89189. });
  89190. if (typeof (VRFrameData) !== "undefined")
  89191. _this._frameData = new VRFrameData();
  89192. /**
  89193. * The idea behind the following lines:
  89194. * objects that have the camera as parent should actually have the rig cameras as a parent.
  89195. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  89196. * the second will not show it correctly.
  89197. *
  89198. * To solve this - each object that has the camera as parent will be added to a protected array.
  89199. * When the rig camera renders, it will take this array and set all of those to be its children.
  89200. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  89201. * Amazing!
  89202. */
  89203. scene.onBeforeCameraRenderObservable.add(function (camera) {
  89204. if (camera.parent === _this && _this.rigParenting) {
  89205. _this._descendants = _this.getDescendants(true, function (n) {
  89206. // don't take the cameras or the controllers!
  89207. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  89208. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  89209. return !isController && !isRigCamera;
  89210. });
  89211. _this._descendants.forEach(function (node) {
  89212. node.parent = camera;
  89213. });
  89214. }
  89215. });
  89216. scene.onAfterCameraRenderObservable.add(function (camera) {
  89217. if (camera.parent === _this && _this.rigParenting) {
  89218. _this._descendants.forEach(function (node) {
  89219. node.parent = _this;
  89220. });
  89221. }
  89222. });
  89223. return _this;
  89224. }
  89225. /**
  89226. * Gets the device distance from the ground in meters.
  89227. * @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.
  89228. */
  89229. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  89230. if (this._standingMatrix) {
  89231. // Add standing matrix offset to get real offset from ground in room
  89232. this._standingMatrix.getTranslationToRef(this._workingVector);
  89233. return this._deviceRoomPosition.y + this._workingVector.y;
  89234. }
  89235. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  89236. return this._defaultHeight || 0;
  89237. };
  89238. /**
  89239. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89240. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  89241. */
  89242. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  89243. var _this = this;
  89244. if (callback === void 0) { callback = function (bool) { }; }
  89245. // Use standing matrix if available
  89246. this.getEngine().initWebVRAsync().then(function (result) {
  89247. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  89248. callback(false);
  89249. }
  89250. else {
  89251. _this._standingMatrix = new BABYLON.Matrix();
  89252. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  89253. if (!_this.getScene().useRightHandedSystem) {
  89254. [2, 6, 8, 9, 14].forEach(function (num) {
  89255. if (_this._standingMatrix) {
  89256. _this._standingMatrix.m[num] *= -1;
  89257. }
  89258. });
  89259. }
  89260. callback(true);
  89261. }
  89262. });
  89263. };
  89264. /**
  89265. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89266. * @returns A promise with a boolean set to if the standing matrix is supported.
  89267. */
  89268. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  89269. var _this = this;
  89270. return new Promise(function (res, rej) {
  89271. _this.useStandingMatrix(function (supported) {
  89272. res(supported);
  89273. });
  89274. });
  89275. };
  89276. /**
  89277. * Disposes the camera
  89278. */
  89279. WebVRFreeCamera.prototype.dispose = function () {
  89280. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  89281. _super.prototype.dispose.call(this);
  89282. };
  89283. /**
  89284. * Gets a vrController by name.
  89285. * @param name The name of the controller to retreive
  89286. * @returns the controller matching the name specified or null if not found
  89287. */
  89288. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  89289. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  89290. var gp = _a[_i];
  89291. if (gp.hand === name) {
  89292. return gp;
  89293. }
  89294. }
  89295. return null;
  89296. };
  89297. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  89298. /**
  89299. * The controller corrisponding to the users left hand.
  89300. */
  89301. get: function () {
  89302. if (!this._leftController) {
  89303. this._leftController = this.getControllerByName("left");
  89304. }
  89305. return this._leftController;
  89306. },
  89307. enumerable: true,
  89308. configurable: true
  89309. });
  89310. ;
  89311. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  89312. /**
  89313. * The controller corrisponding to the users right hand.
  89314. */
  89315. get: function () {
  89316. if (!this._rightController) {
  89317. this._rightController = this.getControllerByName("right");
  89318. }
  89319. return this._rightController;
  89320. },
  89321. enumerable: true,
  89322. configurable: true
  89323. });
  89324. ;
  89325. /**
  89326. * Casts a ray forward from the vrCamera's gaze.
  89327. * @param length Length of the ray (default: 100)
  89328. * @returns the ray corrisponding to the gaze
  89329. */
  89330. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  89331. if (length === void 0) { length = 100; }
  89332. if (this.leftCamera) {
  89333. // Use left eye to avoid computation to compute center on every call
  89334. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  89335. }
  89336. else {
  89337. return _super.prototype.getForwardRay.call(this, length);
  89338. }
  89339. };
  89340. /**
  89341. * Updates the camera based on device's frame data
  89342. */
  89343. WebVRFreeCamera.prototype._checkInputs = function () {
  89344. if (this._vrDevice && this._vrDevice.isPresenting) {
  89345. this._vrDevice.getFrameData(this._frameData);
  89346. this.updateFromDevice(this._frameData.pose);
  89347. }
  89348. _super.prototype._checkInputs.call(this);
  89349. };
  89350. /**
  89351. * Updates the poseControlled values based on the input device pose.
  89352. * @param poseData Pose coming from the device
  89353. */
  89354. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  89355. if (poseData && poseData.orientation) {
  89356. this.rawPose = poseData;
  89357. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  89358. if (this.getScene().useRightHandedSystem) {
  89359. this._deviceRoomRotationQuaternion.z *= -1;
  89360. this._deviceRoomRotationQuaternion.w *= -1;
  89361. }
  89362. if (this.webVROptions.trackPosition && this.rawPose.position) {
  89363. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  89364. if (this.getScene().useRightHandedSystem) {
  89365. this._deviceRoomPosition.z *= -1;
  89366. }
  89367. }
  89368. }
  89369. };
  89370. /**
  89371. * WebVR's attach control will start broadcasting frames to the device.
  89372. * Note that in certain browsers (chrome for example) this function must be called
  89373. * within a user-interaction callback. Example:
  89374. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  89375. *
  89376. * @param element html element to attach the vrDevice to
  89377. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  89378. */
  89379. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  89380. _super.prototype.attachControl.call(this, element, noPreventDefault);
  89381. this._attached = true;
  89382. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  89383. if (this._vrDevice) {
  89384. this.getEngine().enableVR();
  89385. }
  89386. };
  89387. /**
  89388. * Detaches the camera from the html element and disables VR
  89389. *
  89390. * @param element html element to detach from
  89391. */
  89392. WebVRFreeCamera.prototype.detachControl = function (element) {
  89393. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  89394. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  89395. _super.prototype.detachControl.call(this, element);
  89396. this._attached = false;
  89397. this.getEngine().disableVR();
  89398. };
  89399. /**
  89400. * @returns the name of this class
  89401. */
  89402. WebVRFreeCamera.prototype.getClassName = function () {
  89403. return "WebVRFreeCamera";
  89404. };
  89405. /**
  89406. * Calls resetPose on the vrDisplay
  89407. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  89408. */
  89409. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  89410. //uses the vrDisplay's "resetPose()".
  89411. //pitch and roll won't be affected.
  89412. this._vrDevice.resetPose();
  89413. };
  89414. /**
  89415. * Updates the rig cameras (left and right eye)
  89416. */
  89417. WebVRFreeCamera.prototype._updateRigCameras = function () {
  89418. var camLeft = this._rigCameras[0];
  89419. var camRight = this._rigCameras[1];
  89420. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89421. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89422. camLeft.position.copyFrom(this._deviceRoomPosition);
  89423. camRight.position.copyFrom(this._deviceRoomPosition);
  89424. };
  89425. /**
  89426. * Updates the cached values of the camera
  89427. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  89428. */
  89429. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  89430. var _this = this;
  89431. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  89432. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  89433. if (!this.updateCacheCalled) {
  89434. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  89435. this.updateCacheCalled = true;
  89436. this.update();
  89437. }
  89438. // Set working vector to the device position in room space rotated by the new rotation
  89439. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  89440. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  89441. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  89442. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  89443. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  89444. // Add translation from anchor position
  89445. this._deviceToWorld.getTranslationToRef(this._workingVector);
  89446. this._workingVector.addInPlace(this.position);
  89447. this._workingVector.subtractInPlace(this._cache.position);
  89448. this._deviceToWorld.setTranslation(this._workingVector);
  89449. // Set an inverted matrix to be used when updating the camera
  89450. this._deviceToWorld.invertToRef(this._worldToDevice);
  89451. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  89452. this.controllers.forEach(function (controller) {
  89453. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  89454. controller.update();
  89455. });
  89456. }
  89457. if (!ignoreParentClass) {
  89458. _super.prototype._updateCache.call(this);
  89459. }
  89460. this.updateCacheCalled = false;
  89461. };
  89462. /**
  89463. * Updates the current device position and rotation in the babylon world
  89464. */
  89465. WebVRFreeCamera.prototype.update = function () {
  89466. // Get current device position in babylon world
  89467. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  89468. // Get current device rotation in babylon world
  89469. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  89470. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  89471. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  89472. _super.prototype.update.call(this);
  89473. };
  89474. /**
  89475. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  89476. * @returns an identity matrix
  89477. */
  89478. WebVRFreeCamera.prototype._getViewMatrix = function () {
  89479. return BABYLON.Matrix.Identity();
  89480. };
  89481. /**
  89482. * This function is called by the two RIG cameras.
  89483. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  89484. */
  89485. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  89486. var _this = this;
  89487. // Update the parent camera prior to using a child camera to avoid desynchronization
  89488. var parentCamera = this._cameraRigParams["parentCamera"];
  89489. parentCamera._updateCache();
  89490. //WebVR 1.1
  89491. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  89492. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  89493. if (!this.getScene().useRightHandedSystem) {
  89494. [2, 6, 8, 9, 14].forEach(function (num) {
  89495. _this._webvrViewMatrix.m[num] *= -1;
  89496. });
  89497. }
  89498. // update the camera rotation matrix
  89499. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  89500. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  89501. // Computing target and final matrix
  89502. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  89503. // should the view matrix be updated with scale and position offset?
  89504. if (parentCamera.deviceScaleFactor !== 1) {
  89505. this._webvrViewMatrix.invert();
  89506. // scale the position, if set
  89507. if (parentCamera.deviceScaleFactor) {
  89508. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  89509. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  89510. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  89511. }
  89512. this._webvrViewMatrix.invert();
  89513. }
  89514. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  89515. // Compute global position
  89516. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  89517. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  89518. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  89519. this._workingMatrix.getTranslationToRef(this._globalPosition);
  89520. this._markSyncedWithParent();
  89521. return this._webvrViewMatrix;
  89522. };
  89523. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  89524. var _this = this;
  89525. var parentCamera = this.parent;
  89526. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  89527. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  89528. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  89529. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  89530. //babylon compatible matrix
  89531. if (!this.getScene().useRightHandedSystem) {
  89532. [8, 9, 10, 11].forEach(function (num) {
  89533. _this._projectionMatrix.m[num] *= -1;
  89534. });
  89535. }
  89536. return this._projectionMatrix;
  89537. };
  89538. /**
  89539. * Initializes the controllers and their meshes
  89540. */
  89541. WebVRFreeCamera.prototype.initControllers = function () {
  89542. var _this = this;
  89543. this.controllers = [];
  89544. var manager = this.getScene().gamepadManager;
  89545. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  89546. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89547. var webVrController = gamepad;
  89548. if (webVrController.defaultModel) {
  89549. webVrController.defaultModel.setEnabled(false);
  89550. }
  89551. if (webVrController.hand === "right") {
  89552. _this._rightController = null;
  89553. }
  89554. if (webVrController.hand === "left") {
  89555. _this._leftController = null;
  89556. }
  89557. var controllerIndex = _this.controllers.indexOf(webVrController);
  89558. if (controllerIndex !== -1) {
  89559. _this.controllers.splice(controllerIndex, 1);
  89560. }
  89561. }
  89562. });
  89563. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  89564. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89565. var webVrController_1 = gamepad;
  89566. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  89567. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  89568. if (_this.webVROptions.controllerMeshes) {
  89569. if (webVrController_1.defaultModel) {
  89570. webVrController_1.defaultModel.setEnabled(true);
  89571. }
  89572. else {
  89573. // Load the meshes
  89574. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  89575. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  89576. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  89577. if (_this.webVROptions.defaultLightingOnControllers) {
  89578. if (!_this._lightOnControllers) {
  89579. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  89580. }
  89581. var activateLightOnSubMeshes_1 = function (mesh, light) {
  89582. var children = mesh.getChildren();
  89583. if (children.length !== 0) {
  89584. children.forEach(function (mesh) {
  89585. light.includedOnlyMeshes.push(mesh);
  89586. activateLightOnSubMeshes_1(mesh, light);
  89587. });
  89588. }
  89589. };
  89590. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  89591. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  89592. }
  89593. });
  89594. }
  89595. }
  89596. webVrController_1.attachToPoseControlledCamera(_this);
  89597. // since this is async - sanity check. Is the controller already stored?
  89598. if (_this.controllers.indexOf(webVrController_1) === -1) {
  89599. //add to the controllers array
  89600. _this.controllers.push(webVrController_1);
  89601. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  89602. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  89603. // So we're overriding setting left & right manually to be sure
  89604. var firstViveWandDetected = false;
  89605. for (var i = 0; i < _this.controllers.length; i++) {
  89606. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89607. if (!firstViveWandDetected) {
  89608. firstViveWandDetected = true;
  89609. _this.controllers[i].hand = "left";
  89610. }
  89611. else {
  89612. _this.controllers[i].hand = "right";
  89613. }
  89614. }
  89615. }
  89616. //did we find enough controllers? Great! let the developer know.
  89617. if (_this.controllers.length >= 2) {
  89618. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  89619. }
  89620. }
  89621. }
  89622. });
  89623. };
  89624. return WebVRFreeCamera;
  89625. }(BABYLON.FreeCamera));
  89626. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  89627. })(BABYLON || (BABYLON = {}));
  89628. //# sourceMappingURL=babylon.webVRCamera.js.map
  89629. var BABYLON;
  89630. (function (BABYLON) {
  89631. // We're mainly based on the logic defined into the FreeCamera code
  89632. /**
  89633. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  89634. * being tilted forward or back and left or right.
  89635. */
  89636. var DeviceOrientationCamera = /** @class */ (function (_super) {
  89637. __extends(DeviceOrientationCamera, _super);
  89638. /**
  89639. * Creates a new device orientation camera
  89640. * @param name The name of the camera
  89641. * @param position The start position camera
  89642. * @param scene The scene the camera belongs to
  89643. */
  89644. function DeviceOrientationCamera(name, position, scene) {
  89645. var _this = _super.call(this, name, position, scene) || this;
  89646. _this._quaternionCache = new BABYLON.Quaternion();
  89647. _this.inputs.addDeviceOrientation();
  89648. return _this;
  89649. }
  89650. /**
  89651. * Gets the current instance class name ("DeviceOrientationCamera").
  89652. * This helps avoiding instanceof at run time.
  89653. * @returns the class name
  89654. */
  89655. DeviceOrientationCamera.prototype.getClassName = function () {
  89656. return "DeviceOrientationCamera";
  89657. };
  89658. /**
  89659. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  89660. */
  89661. DeviceOrientationCamera.prototype._checkInputs = function () {
  89662. _super.prototype._checkInputs.call(this);
  89663. this._quaternionCache.copyFrom(this.rotationQuaternion);
  89664. if (this._initialQuaternion) {
  89665. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89666. }
  89667. };
  89668. /**
  89669. * Reset the camera to its default orientation on the specified axis only.
  89670. * @param axis The axis to reset
  89671. */
  89672. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  89673. var _this = this;
  89674. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  89675. //can only work if this camera has a rotation quaternion already.
  89676. if (!this.rotationQuaternion)
  89677. return;
  89678. if (!this._initialQuaternion) {
  89679. this._initialQuaternion = new BABYLON.Quaternion();
  89680. }
  89681. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  89682. ['x', 'y', 'z'].forEach(function (axisName) {
  89683. if (!axis[axisName]) {
  89684. _this._initialQuaternion[axisName] = 0;
  89685. }
  89686. else {
  89687. _this._initialQuaternion[axisName] *= -1;
  89688. }
  89689. });
  89690. this._initialQuaternion.normalize();
  89691. //force rotation update
  89692. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89693. };
  89694. return DeviceOrientationCamera;
  89695. }(BABYLON.FreeCamera));
  89696. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  89697. })(BABYLON || (BABYLON = {}));
  89698. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  89699. var BABYLON;
  89700. (function (BABYLON) {
  89701. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  89702. __extends(VRDeviceOrientationFreeCamera, _super);
  89703. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89704. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89705. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89706. var _this = _super.call(this, name, position, scene) || this;
  89707. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89708. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89709. return _this;
  89710. }
  89711. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  89712. return "VRDeviceOrientationFreeCamera";
  89713. };
  89714. return VRDeviceOrientationFreeCamera;
  89715. }(BABYLON.DeviceOrientationCamera));
  89716. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  89717. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  89718. __extends(VRDeviceOrientationGamepadCamera, _super);
  89719. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89720. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89721. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89722. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  89723. _this.inputs.addGamepad();
  89724. return _this;
  89725. }
  89726. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  89727. return "VRDeviceOrientationGamepadCamera";
  89728. };
  89729. return VRDeviceOrientationGamepadCamera;
  89730. }(VRDeviceOrientationFreeCamera));
  89731. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  89732. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  89733. __extends(VRDeviceOrientationArcRotateCamera, _super);
  89734. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  89735. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89736. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89737. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89738. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89739. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89740. _this.inputs.addVRDeviceOrientation();
  89741. return _this;
  89742. }
  89743. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  89744. return "VRDeviceOrientationArcRotateCamera";
  89745. };
  89746. return VRDeviceOrientationArcRotateCamera;
  89747. }(BABYLON.ArcRotateCamera));
  89748. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  89749. })(BABYLON || (BABYLON = {}));
  89750. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  89751. var BABYLON;
  89752. (function (BABYLON) {
  89753. /**
  89754. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  89755. */
  89756. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  89757. __extends(AnaglyphFreeCamera, _super);
  89758. /**
  89759. * Creates a new AnaglyphFreeCamera
  89760. * @param name defines camera name
  89761. * @param position defines initial position
  89762. * @param interaxialDistance defines distance between each color axis
  89763. * @param scene defines the hosting scene
  89764. */
  89765. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  89766. var _this = _super.call(this, name, position, scene) || this;
  89767. _this.interaxialDistance = interaxialDistance;
  89768. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89769. return _this;
  89770. }
  89771. /**
  89772. * Gets camera class name
  89773. * @returns AnaglyphFreeCamera
  89774. */
  89775. AnaglyphFreeCamera.prototype.getClassName = function () {
  89776. return "AnaglyphFreeCamera";
  89777. };
  89778. return AnaglyphFreeCamera;
  89779. }(BABYLON.FreeCamera));
  89780. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  89781. /**
  89782. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  89783. */
  89784. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  89785. __extends(AnaglyphArcRotateCamera, _super);
  89786. /**
  89787. * Creates a new AnaglyphArcRotateCamera
  89788. * @param name defines camera name
  89789. * @param alpha defines alpha angle (in radians)
  89790. * @param beta defines beta angle (in radians)
  89791. * @param radius defines radius
  89792. * @param target defines camera target
  89793. * @param interaxialDistance defines distance between each color axis
  89794. * @param scene defines the hosting scene
  89795. */
  89796. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  89797. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89798. _this.interaxialDistance = interaxialDistance;
  89799. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89800. return _this;
  89801. }
  89802. /**
  89803. * Gets camera class name
  89804. * @returns AnaglyphArcRotateCamera
  89805. */
  89806. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  89807. return "AnaglyphArcRotateCamera";
  89808. };
  89809. return AnaglyphArcRotateCamera;
  89810. }(BABYLON.ArcRotateCamera));
  89811. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  89812. /**
  89813. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  89814. */
  89815. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  89816. __extends(AnaglyphGamepadCamera, _super);
  89817. /**
  89818. * Creates a new AnaglyphGamepadCamera
  89819. * @param name defines camera name
  89820. * @param position defines initial position
  89821. * @param interaxialDistance defines distance between each color axis
  89822. * @param scene defines the hosting scene
  89823. */
  89824. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  89825. var _this = _super.call(this, name, position, scene) || this;
  89826. _this.interaxialDistance = interaxialDistance;
  89827. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89828. return _this;
  89829. }
  89830. /**
  89831. * Gets camera class name
  89832. * @returns AnaglyphGamepadCamera
  89833. */
  89834. AnaglyphGamepadCamera.prototype.getClassName = function () {
  89835. return "AnaglyphGamepadCamera";
  89836. };
  89837. return AnaglyphGamepadCamera;
  89838. }(BABYLON.GamepadCamera));
  89839. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  89840. /**
  89841. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  89842. */
  89843. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  89844. __extends(AnaglyphUniversalCamera, _super);
  89845. /**
  89846. * Creates a new AnaglyphUniversalCamera
  89847. * @param name defines camera name
  89848. * @param position defines initial position
  89849. * @param interaxialDistance defines distance between each color axis
  89850. * @param scene defines the hosting scene
  89851. */
  89852. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  89853. var _this = _super.call(this, name, position, scene) || this;
  89854. _this.interaxialDistance = interaxialDistance;
  89855. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89856. return _this;
  89857. }
  89858. /**
  89859. * Gets camera class name
  89860. * @returns AnaglyphUniversalCamera
  89861. */
  89862. AnaglyphUniversalCamera.prototype.getClassName = function () {
  89863. return "AnaglyphUniversalCamera";
  89864. };
  89865. return AnaglyphUniversalCamera;
  89866. }(BABYLON.UniversalCamera));
  89867. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  89868. /**
  89869. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  89870. */
  89871. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  89872. __extends(StereoscopicFreeCamera, _super);
  89873. /**
  89874. * Creates a new StereoscopicFreeCamera
  89875. * @param name defines camera name
  89876. * @param position defines initial position
  89877. * @param interaxialDistance defines distance between each color axis
  89878. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89879. * @param scene defines the hosting scene
  89880. */
  89881. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89882. var _this = _super.call(this, name, position, scene) || this;
  89883. _this.interaxialDistance = interaxialDistance;
  89884. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89885. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89886. return _this;
  89887. }
  89888. /**
  89889. * Gets camera class name
  89890. * @returns StereoscopicFreeCamera
  89891. */
  89892. StereoscopicFreeCamera.prototype.getClassName = function () {
  89893. return "StereoscopicFreeCamera";
  89894. };
  89895. return StereoscopicFreeCamera;
  89896. }(BABYLON.FreeCamera));
  89897. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  89898. /**
  89899. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  89900. */
  89901. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  89902. __extends(StereoscopicArcRotateCamera, _super);
  89903. /**
  89904. * Creates a new StereoscopicArcRotateCamera
  89905. * @param name defines camera name
  89906. * @param alpha defines alpha angle (in radians)
  89907. * @param beta defines beta angle (in radians)
  89908. * @param radius defines radius
  89909. * @param target defines camera target
  89910. * @param interaxialDistance defines distance between each color axis
  89911. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89912. * @param scene defines the hosting scene
  89913. */
  89914. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  89915. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89916. _this.interaxialDistance = interaxialDistance;
  89917. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89918. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89919. return _this;
  89920. }
  89921. /**
  89922. * Gets camera class name
  89923. * @returns StereoscopicArcRotateCamera
  89924. */
  89925. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  89926. return "StereoscopicArcRotateCamera";
  89927. };
  89928. return StereoscopicArcRotateCamera;
  89929. }(BABYLON.ArcRotateCamera));
  89930. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  89931. /**
  89932. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  89933. */
  89934. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  89935. __extends(StereoscopicGamepadCamera, _super);
  89936. /**
  89937. * Creates a new StereoscopicGamepadCamera
  89938. * @param name defines camera name
  89939. * @param position defines initial position
  89940. * @param interaxialDistance defines distance between each color axis
  89941. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89942. * @param scene defines the hosting scene
  89943. */
  89944. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89945. var _this = _super.call(this, name, position, scene) || this;
  89946. _this.interaxialDistance = interaxialDistance;
  89947. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89948. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89949. return _this;
  89950. }
  89951. /**
  89952. * Gets camera class name
  89953. * @returns StereoscopicGamepadCamera
  89954. */
  89955. StereoscopicGamepadCamera.prototype.getClassName = function () {
  89956. return "StereoscopicGamepadCamera";
  89957. };
  89958. return StereoscopicGamepadCamera;
  89959. }(BABYLON.GamepadCamera));
  89960. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  89961. /**
  89962. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  89963. */
  89964. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  89965. __extends(StereoscopicUniversalCamera, _super);
  89966. /**
  89967. * Creates a new StereoscopicUniversalCamera
  89968. * @param name defines camera name
  89969. * @param position defines initial position
  89970. * @param interaxialDistance defines distance between each color axis
  89971. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89972. * @param scene defines the hosting scene
  89973. */
  89974. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89975. var _this = _super.call(this, name, position, scene) || this;
  89976. _this.interaxialDistance = interaxialDistance;
  89977. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89978. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89979. return _this;
  89980. }
  89981. /**
  89982. * Gets camera class name
  89983. * @returns StereoscopicUniversalCamera
  89984. */
  89985. StereoscopicUniversalCamera.prototype.getClassName = function () {
  89986. return "StereoscopicUniversalCamera";
  89987. };
  89988. return StereoscopicUniversalCamera;
  89989. }(BABYLON.UniversalCamera));
  89990. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  89991. })(BABYLON || (BABYLON = {}));
  89992. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  89993. var BABYLON;
  89994. (function (BABYLON) {
  89995. var VRExperienceHelperGazer = /** @class */ (function () {
  89996. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  89997. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  89998. this.scene = scene;
  89999. this._pointerDownOnMeshAsked = false;
  90000. this._isActionableMesh = false;
  90001. this._teleportationRequestInitiated = false;
  90002. this._teleportationBackRequestInitiated = false;
  90003. this._rotationRightAsked = false;
  90004. this._rotationLeftAsked = false;
  90005. this._dpadPressed = true;
  90006. this._activePointer = false;
  90007. this._id = VRExperienceHelperGazer._idCounter++;
  90008. // Gaze tracker
  90009. if (!gazeTrackerToClone) {
  90010. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  90011. this._gazeTracker.bakeCurrentTransformIntoVertices();
  90012. this._gazeTracker.isPickable = false;
  90013. this._gazeTracker.isVisible = false;
  90014. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  90015. targetMat.specularColor = BABYLON.Color3.Black();
  90016. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  90017. targetMat.backFaceCulling = false;
  90018. this._gazeTracker.material = targetMat;
  90019. }
  90020. else {
  90021. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  90022. }
  90023. }
  90024. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  90025. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  90026. };
  90027. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  90028. this._pointerDownOnMeshAsked = true;
  90029. if (this._currentHit) {
  90030. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  90031. }
  90032. };
  90033. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  90034. if (this._currentHit) {
  90035. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  90036. }
  90037. this._pointerDownOnMeshAsked = false;
  90038. };
  90039. VRExperienceHelperGazer.prototype._activatePointer = function () {
  90040. this._activePointer = true;
  90041. };
  90042. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  90043. this._activePointer = false;
  90044. };
  90045. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  90046. if (distance === void 0) { distance = 100; }
  90047. };
  90048. VRExperienceHelperGazer.prototype.dispose = function () {
  90049. this._interactionsEnabled = false;
  90050. this._teleportationEnabled = false;
  90051. if (this._gazeTracker) {
  90052. this._gazeTracker.dispose();
  90053. }
  90054. };
  90055. VRExperienceHelperGazer._idCounter = 0;
  90056. return VRExperienceHelperGazer;
  90057. }());
  90058. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  90059. __extends(VRExperienceHelperControllerGazer, _super);
  90060. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  90061. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  90062. _this.webVRController = webVRController;
  90063. // Laser pointer
  90064. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  90065. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  90066. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  90067. laserPointerMaterial.alpha = 0.6;
  90068. _this._laserPointer.material = laserPointerMaterial;
  90069. _this._laserPointer.rotation.x = Math.PI / 2;
  90070. _this._laserPointer.position.z = -0.5;
  90071. _this._laserPointer.isVisible = false;
  90072. if (!webVRController.mesh) {
  90073. // Create an empty mesh that is used prior to loading the high quality model
  90074. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  90075. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  90076. preloadPointerPose.rotation.x = -0.7;
  90077. preloadMesh.addChild(preloadPointerPose);
  90078. webVRController.attachToMesh(preloadMesh);
  90079. }
  90080. _this._setLaserPointerParent(webVRController.mesh);
  90081. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  90082. _this._setLaserPointerParent(mesh);
  90083. });
  90084. return _this;
  90085. }
  90086. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  90087. return this.webVRController.getForwardRay(length);
  90088. };
  90089. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  90090. _super.prototype._activatePointer.call(this);
  90091. this._laserPointer.isVisible = true;
  90092. };
  90093. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  90094. _super.prototype._deactivatePointer.call(this);
  90095. this._laserPointer.isVisible = false;
  90096. };
  90097. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  90098. this._laserPointer.material.emissiveColor = color;
  90099. };
  90100. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  90101. var makeNotPick = function (root) {
  90102. root.name += " laserPointer";
  90103. root.getChildMeshes().forEach(function (c) {
  90104. makeNotPick(c);
  90105. });
  90106. };
  90107. makeNotPick(mesh);
  90108. var childMeshes = mesh.getChildMeshes();
  90109. this.webVRController._pointingPoseNode = null;
  90110. for (var i = 0; i < childMeshes.length; i++) {
  90111. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  90112. mesh = childMeshes[i];
  90113. this.webVRController._pointingPoseNode = mesh;
  90114. break;
  90115. }
  90116. }
  90117. this._laserPointer.parent = mesh;
  90118. };
  90119. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  90120. if (distance === void 0) { distance = 100; }
  90121. this._laserPointer.scaling.y = distance;
  90122. this._laserPointer.position.z = -distance / 2;
  90123. };
  90124. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  90125. _super.prototype.dispose.call(this);
  90126. this._laserPointer.dispose();
  90127. if (this._meshAttachedObserver) {
  90128. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  90129. }
  90130. };
  90131. return VRExperienceHelperControllerGazer;
  90132. }(VRExperienceHelperGazer));
  90133. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  90134. __extends(VRExperienceHelperCameraGazer, _super);
  90135. function VRExperienceHelperCameraGazer(getCamera, scene) {
  90136. var _this = _super.call(this, scene) || this;
  90137. _this.getCamera = getCamera;
  90138. return _this;
  90139. }
  90140. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  90141. var camera = this.getCamera();
  90142. if (camera) {
  90143. return camera.getForwardRay(length);
  90144. }
  90145. else {
  90146. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  90147. }
  90148. };
  90149. return VRExperienceHelperCameraGazer;
  90150. }(VRExperienceHelperGazer));
  90151. /**
  90152. * Helps to quickly add VR support to an existing scene.
  90153. * See http://doc.babylonjs.com/how_to/webvr_helper
  90154. */
  90155. var VRExperienceHelper = /** @class */ (function () {
  90156. /**
  90157. * Instantiates a VRExperienceHelper.
  90158. * Helps to quickly add VR support to an existing scene.
  90159. * @param scene The scene the VRExperienceHelper belongs to.
  90160. * @param webVROptions Options to modify the vr experience helper's behavior.
  90161. */
  90162. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  90163. if (webVROptions === void 0) { webVROptions = {}; }
  90164. var _this = this;
  90165. this.webVROptions = webVROptions;
  90166. // Can the system support WebVR, even if a headset isn't plugged in?
  90167. this._webVRsupported = false;
  90168. // If WebVR is supported, is a headset plugged in and are we ready to present?
  90169. this._webVRready = false;
  90170. // Are we waiting for the requestPresent callback to complete?
  90171. this._webVRrequesting = false;
  90172. // Are we presenting to the headset right now?
  90173. this._webVRpresenting = false;
  90174. // Are we presenting in the fullscreen fallback?
  90175. this._fullscreenVRpresenting = false;
  90176. /**
  90177. * Observable raised when entering VR.
  90178. */
  90179. this.onEnteringVRObservable = new BABYLON.Observable();
  90180. /**
  90181. * Observable raised when exiting VR.
  90182. */
  90183. this.onExitingVRObservable = new BABYLON.Observable();
  90184. /**
  90185. * Observable raised when controller mesh is loaded.
  90186. */
  90187. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90188. this._useCustomVRButton = false;
  90189. this._teleportationRequested = false;
  90190. this._teleportActive = false;
  90191. this._floorMeshesCollection = [];
  90192. this._rotationAllowed = true;
  90193. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  90194. this._isDefaultTeleportationTarget = true;
  90195. this._teleportationFillColor = "#444444";
  90196. this._teleportationBorderColor = "#FFFFFF";
  90197. this._rotationAngle = 0;
  90198. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  90199. this._padSensibilityUp = 0.65;
  90200. this._padSensibilityDown = 0.35;
  90201. this.leftController = null;
  90202. this.rightController = null;
  90203. /**
  90204. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  90205. */
  90206. this.onNewMeshSelected = new BABYLON.Observable();
  90207. /**
  90208. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  90209. */
  90210. this.onNewMeshPicked = new BABYLON.Observable();
  90211. /**
  90212. * Observable raised before camera teleportation
  90213. */
  90214. this.onBeforeCameraTeleport = new BABYLON.Observable();
  90215. /**
  90216. * Observable raised after camera teleportation
  90217. */
  90218. this.onAfterCameraTeleport = new BABYLON.Observable();
  90219. /**
  90220. * Observable raised when current selected mesh gets unselected
  90221. */
  90222. this.onSelectedMeshUnselected = new BABYLON.Observable();
  90223. /**
  90224. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  90225. */
  90226. this.teleportationEnabled = true;
  90227. this._teleportationInitialized = false;
  90228. this._interactionsEnabled = false;
  90229. this._interactionsRequested = false;
  90230. this._displayGaze = true;
  90231. this._displayLaserPointer = true;
  90232. this._onResize = function () {
  90233. _this.moveButtonToBottomRight();
  90234. if (_this._fullscreenVRpresenting && _this._webVRready) {
  90235. _this.exitVR();
  90236. }
  90237. };
  90238. this._onFullscreenChange = function () {
  90239. if (document.fullscreen !== undefined) {
  90240. _this._fullscreenVRpresenting = document.fullscreen;
  90241. }
  90242. else if (document.mozFullScreen !== undefined) {
  90243. _this._fullscreenVRpresenting = document.mozFullScreen;
  90244. }
  90245. else if (document.webkitIsFullScreen !== undefined) {
  90246. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  90247. }
  90248. else if (document.msIsFullScreen !== undefined) {
  90249. _this._fullscreenVRpresenting = document.msIsFullScreen;
  90250. }
  90251. if (!_this._fullscreenVRpresenting && _this._canvas) {
  90252. _this.exitVR();
  90253. if (!_this._useCustomVRButton) {
  90254. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  90255. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  90256. }
  90257. }
  90258. };
  90259. this.beforeRender = function () {
  90260. if (_this.leftController && _this.leftController._activePointer) {
  90261. _this._castRayAndSelectObject(_this.leftController);
  90262. }
  90263. if (_this.rightController && _this.rightController._activePointer) {
  90264. _this._castRayAndSelectObject(_this.rightController);
  90265. }
  90266. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  90267. _this._castRayAndSelectObject(_this._cameraGazer);
  90268. }
  90269. else {
  90270. _this._cameraGazer._gazeTracker.isVisible = false;
  90271. }
  90272. };
  90273. this._onNewGamepadConnected = function (gamepad) {
  90274. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  90275. if (gamepad.leftStick) {
  90276. gamepad.onleftstickchanged(function (stickValues) {
  90277. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  90278. // Listening to classic/xbox gamepad only if no VR controller is active
  90279. if ((!_this.leftController && !_this.rightController) ||
  90280. ((_this.leftController && !_this.leftController._activePointer) &&
  90281. (_this.rightController && !_this.rightController._activePointer))) {
  90282. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  90283. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  90284. }
  90285. }
  90286. });
  90287. }
  90288. if (gamepad.rightStick) {
  90289. gamepad.onrightstickchanged(function (stickValues) {
  90290. if (_this._teleportationInitialized) {
  90291. _this._checkRotate(stickValues, _this._cameraGazer);
  90292. }
  90293. });
  90294. }
  90295. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  90296. gamepad.onbuttondown(function (buttonPressed) {
  90297. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90298. _this._cameraGazer._selectionPointerDown();
  90299. }
  90300. });
  90301. gamepad.onbuttonup(function (buttonPressed) {
  90302. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90303. _this._cameraGazer._selectionPointerUp();
  90304. }
  90305. });
  90306. }
  90307. }
  90308. else {
  90309. var webVRController = gamepad;
  90310. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  90311. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  90312. _this.rightController = controller;
  90313. }
  90314. else {
  90315. _this.leftController = controller;
  90316. }
  90317. _this._tryEnableInteractionOnController(controller);
  90318. }
  90319. };
  90320. // 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
  90321. this._tryEnableInteractionOnController = function (controller) {
  90322. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  90323. _this._enableInteractionOnController(controller);
  90324. }
  90325. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  90326. _this._enableTeleportationOnController(controller);
  90327. }
  90328. };
  90329. this._onNewGamepadDisconnected = function (gamepad) {
  90330. if (gamepad instanceof BABYLON.WebVRController) {
  90331. if (gamepad.hand === "left" && _this.leftController != null) {
  90332. _this.leftController.dispose();
  90333. _this.leftController = null;
  90334. }
  90335. if (gamepad.hand === "right" && _this.rightController != null) {
  90336. _this.rightController.dispose();
  90337. _this.rightController = null;
  90338. }
  90339. }
  90340. };
  90341. this._workingVector = BABYLON.Vector3.Zero();
  90342. this._workingQuaternion = BABYLON.Quaternion.Identity();
  90343. this._workingMatrix = BABYLON.Matrix.Identity();
  90344. this._scene = scene;
  90345. this._canvas = scene.getEngine().getRenderingCanvas();
  90346. // Parse options
  90347. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  90348. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  90349. }
  90350. if (webVROptions.createDeviceOrientationCamera === undefined) {
  90351. webVROptions.createDeviceOrientationCamera = true;
  90352. }
  90353. if (webVROptions.laserToggle === undefined) {
  90354. webVROptions.laserToggle = true;
  90355. }
  90356. if (webVROptions.defaultHeight === undefined) {
  90357. webVROptions.defaultHeight = 1.7;
  90358. }
  90359. if (webVROptions.useCustomVRButton) {
  90360. this._useCustomVRButton = true;
  90361. if (webVROptions.customVRButton) {
  90362. this._btnVR = webVROptions.customVRButton;
  90363. }
  90364. }
  90365. if (webVROptions.rayLength) {
  90366. this._rayLength = webVROptions.rayLength;
  90367. }
  90368. this._defaultHeight = webVROptions.defaultHeight;
  90369. if (webVROptions.positionScale) {
  90370. this._rayLength *= webVROptions.positionScale;
  90371. this._defaultHeight *= webVROptions.positionScale;
  90372. }
  90373. // Set position
  90374. if (this._scene.activeCamera) {
  90375. this._position = this._scene.activeCamera.position.clone();
  90376. }
  90377. else {
  90378. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  90379. }
  90380. // Set non-vr camera
  90381. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  90382. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  90383. // Copy data from existing camera
  90384. if (this._scene.activeCamera) {
  90385. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90386. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  90387. // Set rotation from previous camera
  90388. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  90389. var targetCamera = this._scene.activeCamera;
  90390. if (targetCamera.rotationQuaternion) {
  90391. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  90392. }
  90393. else {
  90394. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  90395. }
  90396. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  90397. }
  90398. }
  90399. this._scene.activeCamera = this._deviceOrientationCamera;
  90400. if (this._canvas) {
  90401. this._scene.activeCamera.attachControl(this._canvas);
  90402. }
  90403. }
  90404. else {
  90405. this._existingCamera = this._scene.activeCamera;
  90406. }
  90407. // Create VR cameras
  90408. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90409. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  90410. }
  90411. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  90412. this._webVRCamera.useStandingMatrix();
  90413. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  90414. // Create default button
  90415. if (!this._useCustomVRButton) {
  90416. this._btnVR = document.createElement("BUTTON");
  90417. this._btnVR.className = "babylonVRicon";
  90418. this._btnVR.id = "babylonVRiconbtn";
  90419. this._btnVR.title = "Click to switch to VR";
  90420. 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) }";
  90421. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  90422. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  90423. // css += ".babylonVRicon.vrdisplaysupported { }";
  90424. // css += ".babylonVRicon.vrdisplayready { }";
  90425. // css += ".babylonVRicon.vrdisplayrequesting { }";
  90426. var style = document.createElement('style');
  90427. style.appendChild(document.createTextNode(css));
  90428. document.getElementsByTagName('head')[0].appendChild(style);
  90429. this.moveButtonToBottomRight();
  90430. }
  90431. // VR button click event
  90432. if (this._btnVR) {
  90433. this._btnVR.addEventListener("click", function () {
  90434. if (!_this.isInVRMode) {
  90435. _this.enterVR();
  90436. }
  90437. else {
  90438. _this.exitVR();
  90439. }
  90440. });
  90441. }
  90442. // Window events
  90443. window.addEventListener("resize", this._onResize);
  90444. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  90445. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  90446. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  90447. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  90448. // Display vr button when headset is connected
  90449. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90450. this.displayVRButton();
  90451. }
  90452. else {
  90453. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  90454. if (e.vrDisplay) {
  90455. _this.displayVRButton();
  90456. }
  90457. });
  90458. }
  90459. // Exiting VR mode using 'ESC' key on desktop
  90460. this._onKeyDown = function (event) {
  90461. if (event.keyCode === 27 && _this.isInVRMode) {
  90462. _this.exitVR();
  90463. }
  90464. };
  90465. document.addEventListener("keydown", this._onKeyDown);
  90466. // Exiting VR mode double tapping the touch screen
  90467. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  90468. if (_this.isInVRMode) {
  90469. _this.exitVR();
  90470. if (_this._fullscreenVRpresenting) {
  90471. _this._scene.getEngine().switchFullscreen(true);
  90472. }
  90473. }
  90474. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  90475. // Listen for WebVR display changes
  90476. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  90477. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  90478. this._onVRRequestPresentStart = function () {
  90479. _this._webVRrequesting = true;
  90480. _this.updateButtonVisibility();
  90481. };
  90482. this._onVRRequestPresentComplete = function (success) {
  90483. _this._webVRrequesting = false;
  90484. _this.updateButtonVisibility();
  90485. };
  90486. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  90487. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  90488. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  90489. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90490. scene.onDisposeObservable.add(function () {
  90491. _this.dispose();
  90492. });
  90493. // Gamepad connection events
  90494. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  90495. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  90496. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  90497. this.updateButtonVisibility();
  90498. //create easing functions
  90499. this._circleEase = new BABYLON.CircleEase();
  90500. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90501. if (this.webVROptions.floorMeshes) {
  90502. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  90503. }
  90504. }
  90505. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  90506. /** Return this.onEnteringVRObservable
  90507. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  90508. */
  90509. get: function () {
  90510. return this.onEnteringVRObservable;
  90511. },
  90512. enumerable: true,
  90513. configurable: true
  90514. });
  90515. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  90516. /** Return this.onExitingVRObservable
  90517. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  90518. */
  90519. get: function () {
  90520. return this.onExitingVRObservable;
  90521. },
  90522. enumerable: true,
  90523. configurable: true
  90524. });
  90525. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  90526. /** Return this.onControllerMeshLoadedObservable
  90527. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  90528. */
  90529. get: function () {
  90530. return this.onControllerMeshLoadedObservable;
  90531. },
  90532. enumerable: true,
  90533. configurable: true
  90534. });
  90535. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  90536. /**
  90537. * The mesh used to display where the user is going to teleport.
  90538. */
  90539. get: function () {
  90540. return this._teleportationTarget;
  90541. },
  90542. /**
  90543. * Sets the mesh to be used to display where the user is going to teleport.
  90544. */
  90545. set: function (value) {
  90546. if (value) {
  90547. value.name = "teleportationTarget";
  90548. this._isDefaultTeleportationTarget = false;
  90549. this._teleportationTarget = value;
  90550. }
  90551. },
  90552. enumerable: true,
  90553. configurable: true
  90554. });
  90555. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  90556. /**
  90557. * The mesh used to display where the user is selecting,
  90558. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  90559. * See http://doc.babylonjs.com/resources/baking_transformations
  90560. */
  90561. get: function () {
  90562. return this._cameraGazer._gazeTracker;
  90563. },
  90564. set: function (value) {
  90565. if (value) {
  90566. this._cameraGazer._gazeTracker = value;
  90567. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  90568. this._cameraGazer._gazeTracker.isPickable = false;
  90569. this._cameraGazer._gazeTracker.isVisible = false;
  90570. this._cameraGazer._gazeTracker.name = "gazeTracker";
  90571. if (this.leftController) {
  90572. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90573. }
  90574. if (this.rightController) {
  90575. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90576. }
  90577. }
  90578. },
  90579. enumerable: true,
  90580. configurable: true
  90581. });
  90582. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  90583. /**
  90584. * If the ray of the gaze should be displayed.
  90585. */
  90586. get: function () {
  90587. return this._displayGaze;
  90588. },
  90589. /**
  90590. * Sets if the ray of the gaze should be displayed.
  90591. */
  90592. set: function (value) {
  90593. this._displayGaze = value;
  90594. if (!value) {
  90595. this._cameraGazer._gazeTracker.isVisible = false;
  90596. if (this.leftController) {
  90597. this.leftController._gazeTracker.isVisible = false;
  90598. }
  90599. if (this.rightController) {
  90600. this.rightController._gazeTracker.isVisible = false;
  90601. }
  90602. }
  90603. },
  90604. enumerable: true,
  90605. configurable: true
  90606. });
  90607. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  90608. /**
  90609. * If the ray of the LaserPointer should be displayed.
  90610. */
  90611. get: function () {
  90612. return this._displayLaserPointer;
  90613. },
  90614. /**
  90615. * Sets if the ray of the LaserPointer should be displayed.
  90616. */
  90617. set: function (value) {
  90618. this._displayLaserPointer = value;
  90619. if (!value) {
  90620. if (this.rightController) {
  90621. this.rightController._deactivatePointer();
  90622. this.rightController._gazeTracker.isVisible = false;
  90623. }
  90624. if (this.leftController) {
  90625. this.leftController._deactivatePointer();
  90626. this.leftController._gazeTracker.isVisible = false;
  90627. }
  90628. }
  90629. else {
  90630. if (this.rightController) {
  90631. this.rightController._activatePointer();
  90632. }
  90633. if (this.leftController) {
  90634. this.leftController._activatePointer();
  90635. }
  90636. }
  90637. },
  90638. enumerable: true,
  90639. configurable: true
  90640. });
  90641. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  90642. /**
  90643. * The deviceOrientationCamera used as the camera when not in VR.
  90644. */
  90645. get: function () {
  90646. return this._deviceOrientationCamera;
  90647. },
  90648. enumerable: true,
  90649. configurable: true
  90650. });
  90651. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  90652. /**
  90653. * Based on the current WebVR support, returns the current VR camera used.
  90654. */
  90655. get: function () {
  90656. if (this._webVRready) {
  90657. return this._webVRCamera;
  90658. }
  90659. else {
  90660. return this._scene.activeCamera;
  90661. }
  90662. },
  90663. enumerable: true,
  90664. configurable: true
  90665. });
  90666. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  90667. /**
  90668. * The webVRCamera which is used when in VR.
  90669. */
  90670. get: function () {
  90671. return this._webVRCamera;
  90672. },
  90673. enumerable: true,
  90674. configurable: true
  90675. });
  90676. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  90677. /**
  90678. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  90679. */
  90680. get: function () {
  90681. return this._vrDeviceOrientationCamera;
  90682. },
  90683. enumerable: true,
  90684. configurable: true
  90685. });
  90686. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  90687. get: function () {
  90688. var result = this._cameraGazer._teleportationRequestInitiated
  90689. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  90690. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  90691. return result;
  90692. },
  90693. enumerable: true,
  90694. configurable: true
  90695. });
  90696. // Raised when one of the controller has loaded successfully its associated default mesh
  90697. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  90698. if (this.leftController && this.leftController.webVRController == webVRController) {
  90699. if (webVRController.mesh) {
  90700. this.leftController._setLaserPointerParent(webVRController.mesh);
  90701. }
  90702. }
  90703. if (this.rightController && this.rightController.webVRController == webVRController) {
  90704. if (webVRController.mesh) {
  90705. this.rightController._setLaserPointerParent(webVRController.mesh);
  90706. }
  90707. }
  90708. try {
  90709. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  90710. }
  90711. catch (err) {
  90712. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  90713. }
  90714. };
  90715. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  90716. /**
  90717. * Gets a value indicating if we are currently in VR mode.
  90718. */
  90719. get: function () {
  90720. return this._webVRpresenting || this._fullscreenVRpresenting;
  90721. },
  90722. enumerable: true,
  90723. configurable: true
  90724. });
  90725. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  90726. var vrDisplay = this._scene.getEngine().getVRDevice();
  90727. if (vrDisplay) {
  90728. var wasPresenting = this._webVRpresenting;
  90729. // A VR display is connected
  90730. this._webVRpresenting = vrDisplay.isPresenting;
  90731. if (wasPresenting && !this._webVRpresenting)
  90732. this.exitVR();
  90733. }
  90734. else {
  90735. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  90736. }
  90737. this.updateButtonVisibility();
  90738. };
  90739. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  90740. this._webVRsupported = eventArgs.vrSupported;
  90741. this._webVRready = !!eventArgs.vrDisplay;
  90742. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  90743. this.updateButtonVisibility();
  90744. };
  90745. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  90746. if (this._canvas && !this._useCustomVRButton) {
  90747. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  90748. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  90749. }
  90750. };
  90751. VRExperienceHelper.prototype.displayVRButton = function () {
  90752. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  90753. document.body.appendChild(this._btnVR);
  90754. this._btnVRDisplayed = true;
  90755. }
  90756. };
  90757. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  90758. if (!this._btnVR || this._useCustomVRButton) {
  90759. return;
  90760. }
  90761. this._btnVR.className = "babylonVRicon";
  90762. if (this.isInVRMode) {
  90763. this._btnVR.className += " vrdisplaypresenting";
  90764. }
  90765. else {
  90766. if (this._webVRready)
  90767. this._btnVR.className += " vrdisplayready";
  90768. if (this._webVRsupported)
  90769. this._btnVR.className += " vrdisplaysupported";
  90770. if (this._webVRrequesting)
  90771. this._btnVR.className += " vrdisplayrequesting";
  90772. }
  90773. };
  90774. /**
  90775. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  90776. * Otherwise, will use the fullscreen API.
  90777. */
  90778. VRExperienceHelper.prototype.enterVR = function () {
  90779. if (this.onEnteringVRObservable) {
  90780. try {
  90781. this.onEnteringVRObservable.notifyObservers(this);
  90782. }
  90783. catch (err) {
  90784. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  90785. }
  90786. }
  90787. if (this._scene.activeCamera) {
  90788. this._position = this._scene.activeCamera.position.clone();
  90789. // make sure that we return to the last active camera
  90790. this._existingCamera = this._scene.activeCamera;
  90791. }
  90792. if (this._webVRrequesting)
  90793. return;
  90794. // If WebVR is supported and a headset is connected
  90795. if (this._webVRready) {
  90796. if (!this._webVRpresenting) {
  90797. this._webVRCamera.position = this._position;
  90798. this._scene.activeCamera = this._webVRCamera;
  90799. }
  90800. }
  90801. else if (this._vrDeviceOrientationCamera) {
  90802. this._vrDeviceOrientationCamera.position = this._position;
  90803. if (this._scene.activeCamera) {
  90804. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90805. }
  90806. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  90807. this._scene.getEngine().switchFullscreen(true);
  90808. this.updateButtonVisibility();
  90809. }
  90810. if (this._scene.activeCamera && this._canvas) {
  90811. this._scene.activeCamera.attachControl(this._canvas);
  90812. }
  90813. if (this._interactionsEnabled) {
  90814. this._scene.registerBeforeRender(this.beforeRender);
  90815. }
  90816. };
  90817. /**
  90818. * Attempt to exit VR, or fullscreen.
  90819. */
  90820. VRExperienceHelper.prototype.exitVR = function () {
  90821. if (this.onExitingVRObservable) {
  90822. try {
  90823. this.onExitingVRObservable.notifyObservers(this);
  90824. }
  90825. catch (err) {
  90826. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  90827. }
  90828. }
  90829. if (this._webVRpresenting) {
  90830. this._scene.getEngine().disableVR();
  90831. }
  90832. if (this._scene.activeCamera) {
  90833. this._position = this._scene.activeCamera.position.clone();
  90834. }
  90835. if (this._deviceOrientationCamera) {
  90836. this._deviceOrientationCamera.position = this._position;
  90837. this._scene.activeCamera = this._deviceOrientationCamera;
  90838. if (this._canvas) {
  90839. this._scene.activeCamera.attachControl(this._canvas);
  90840. }
  90841. }
  90842. else if (this._existingCamera) {
  90843. this._existingCamera.position = this._position;
  90844. this._scene.activeCamera = this._existingCamera;
  90845. }
  90846. this.updateButtonVisibility();
  90847. if (this._interactionsEnabled) {
  90848. this._scene.unregisterBeforeRender(this.beforeRender);
  90849. }
  90850. // resize to update width and height when exiting vr exits fullscreen
  90851. this._scene.getEngine().resize();
  90852. };
  90853. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  90854. /**
  90855. * The position of the vr experience helper.
  90856. */
  90857. get: function () {
  90858. return this._position;
  90859. },
  90860. /**
  90861. * Sets the position of the vr experience helper.
  90862. */
  90863. set: function (value) {
  90864. this._position = value;
  90865. if (this._scene.activeCamera) {
  90866. this._scene.activeCamera.position = value;
  90867. }
  90868. },
  90869. enumerable: true,
  90870. configurable: true
  90871. });
  90872. /**
  90873. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  90874. */
  90875. VRExperienceHelper.prototype.enableInteractions = function () {
  90876. var _this = this;
  90877. if (!this._interactionsEnabled) {
  90878. this._interactionsRequested = true;
  90879. if (this.leftController) {
  90880. this._enableInteractionOnController(this.leftController);
  90881. }
  90882. if (this.rightController) {
  90883. this._enableInteractionOnController(this.rightController);
  90884. }
  90885. this.raySelectionPredicate = function (mesh) {
  90886. return mesh.isVisible;
  90887. };
  90888. this.meshSelectionPredicate = function (mesh) {
  90889. return true;
  90890. };
  90891. this._raySelectionPredicate = function (mesh) {
  90892. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  90893. && mesh.name.indexOf("teleportationTarget") === -1
  90894. && mesh.name.indexOf("torusTeleportation") === -1
  90895. && mesh.name.indexOf("laserPointer") === -1)) {
  90896. return _this.raySelectionPredicate(mesh);
  90897. }
  90898. return false;
  90899. };
  90900. this._interactionsEnabled = true;
  90901. }
  90902. };
  90903. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  90904. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  90905. if (this._floorMeshesCollection[i].id === mesh.id) {
  90906. return true;
  90907. }
  90908. }
  90909. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  90910. return true;
  90911. }
  90912. return false;
  90913. };
  90914. /**
  90915. * Adds a floor mesh to be used for teleportation.
  90916. * @param floorMesh the mesh to be used for teleportation.
  90917. */
  90918. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  90919. if (!this._floorMeshesCollection) {
  90920. return;
  90921. }
  90922. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  90923. return;
  90924. }
  90925. this._floorMeshesCollection.push(floorMesh);
  90926. };
  90927. /**
  90928. * Removes a floor mesh from being used for teleportation.
  90929. * @param floorMesh the mesh to be removed.
  90930. */
  90931. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  90932. if (!this._floorMeshesCollection) {
  90933. return;
  90934. }
  90935. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  90936. if (meshIndex !== -1) {
  90937. this._floorMeshesCollection.splice(meshIndex, 1);
  90938. }
  90939. };
  90940. /**
  90941. * Enables interactions and teleportation using the VR controllers and gaze.
  90942. * @param vrTeleportationOptions options to modify teleportation behavior.
  90943. */
  90944. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  90945. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  90946. if (!this._teleportationInitialized) {
  90947. this._teleportationRequested = true;
  90948. this.enableInteractions();
  90949. if (vrTeleportationOptions.floorMeshName) {
  90950. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  90951. }
  90952. if (vrTeleportationOptions.floorMeshes) {
  90953. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  90954. }
  90955. if (this.leftController != null) {
  90956. this._enableTeleportationOnController(this.leftController);
  90957. }
  90958. if (this.rightController != null) {
  90959. this._enableTeleportationOnController(this.rightController);
  90960. }
  90961. // Creates an image processing post process for the vignette not relying
  90962. // on the main scene configuration for image processing to reduce setup and spaces
  90963. // (gamma/linear) conflicts.
  90964. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  90965. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  90966. imageProcessingConfiguration.vignetteEnabled = true;
  90967. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  90968. this._webVRCamera.detachPostProcess(this._postProcessMove);
  90969. this._teleportationInitialized = true;
  90970. if (this._isDefaultTeleportationTarget) {
  90971. this._createTeleportationCircles();
  90972. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  90973. }
  90974. }
  90975. };
  90976. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  90977. var _this = this;
  90978. var controllerMesh = controller.webVRController.mesh;
  90979. if (controllerMesh) {
  90980. controller._interactionsEnabled = true;
  90981. controller._activatePointer();
  90982. if (this.webVROptions.laserToggle) {
  90983. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  90984. // Enabling / disabling laserPointer
  90985. if (_this._displayLaserPointer && stateObject.value === 1) {
  90986. if (controller._activePointer) {
  90987. controller._deactivatePointer();
  90988. }
  90989. else {
  90990. controller._activatePointer();
  90991. }
  90992. if (_this.displayGaze) {
  90993. controller._gazeTracker.isVisible = controller._activePointer;
  90994. }
  90995. }
  90996. });
  90997. }
  90998. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  90999. if (!controller._pointerDownOnMeshAsked) {
  91000. if (stateObject.value > _this._padSensibilityUp) {
  91001. controller._selectionPointerDown();
  91002. }
  91003. }
  91004. else if (stateObject.value < _this._padSensibilityDown) {
  91005. controller._selectionPointerUp();
  91006. }
  91007. });
  91008. }
  91009. };
  91010. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  91011. // Dont teleport if another gaze already requested teleportation
  91012. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  91013. return;
  91014. }
  91015. if (!gazer._teleportationRequestInitiated) {
  91016. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  91017. gazer._activatePointer();
  91018. gazer._teleportationRequestInitiated = true;
  91019. }
  91020. }
  91021. else {
  91022. // Listening to the proper controller values changes to confirm teleportation
  91023. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  91024. if (this._teleportActive) {
  91025. this._teleportCamera(this._haloCenter);
  91026. }
  91027. gazer._teleportationRequestInitiated = false;
  91028. }
  91029. }
  91030. };
  91031. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  91032. // Only rotate when user is not currently selecting a teleportation location
  91033. if (gazer._teleportationRequestInitiated) {
  91034. return;
  91035. }
  91036. if (!gazer._rotationLeftAsked) {
  91037. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  91038. gazer._rotationLeftAsked = true;
  91039. if (this._rotationAllowed) {
  91040. this._rotateCamera(false);
  91041. }
  91042. }
  91043. }
  91044. else {
  91045. if (stateObject.x > -this._padSensibilityDown) {
  91046. gazer._rotationLeftAsked = false;
  91047. }
  91048. }
  91049. if (!gazer._rotationRightAsked) {
  91050. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  91051. gazer._rotationRightAsked = true;
  91052. if (this._rotationAllowed) {
  91053. this._rotateCamera(true);
  91054. }
  91055. }
  91056. }
  91057. else {
  91058. if (stateObject.x < this._padSensibilityDown) {
  91059. gazer._rotationRightAsked = false;
  91060. }
  91061. }
  91062. };
  91063. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  91064. // Only teleport backwards when user is not currently selecting a teleportation location
  91065. if (gazer._teleportationRequestInitiated) {
  91066. return;
  91067. }
  91068. // Teleport backwards
  91069. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  91070. if (!gazer._teleportationBackRequestInitiated) {
  91071. if (!this.currentVRCamera) {
  91072. return;
  91073. }
  91074. // Get rotation and position of the current camera
  91075. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  91076. var position = this.currentVRCamera.position;
  91077. // If the camera has device position, use that instead
  91078. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  91079. rotation = this.currentVRCamera.deviceRotationQuaternion;
  91080. position = this.currentVRCamera.devicePosition;
  91081. }
  91082. // Get matrix with only the y rotation of the device rotation
  91083. rotation.toEulerAnglesToRef(this._workingVector);
  91084. this._workingVector.z = 0;
  91085. this._workingVector.x = 0;
  91086. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  91087. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  91088. // Rotate backwards ray by device rotation to cast at the ground behind the user
  91089. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  91090. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  91091. var ray = new BABYLON.Ray(position, this._workingVector);
  91092. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91093. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  91094. this._teleportCamera(hit.pickedPoint);
  91095. }
  91096. gazer._teleportationBackRequestInitiated = true;
  91097. }
  91098. }
  91099. else {
  91100. gazer._teleportationBackRequestInitiated = false;
  91101. }
  91102. };
  91103. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  91104. var _this = this;
  91105. var controllerMesh = controller.webVRController.mesh;
  91106. if (controllerMesh) {
  91107. if (!controller._interactionsEnabled) {
  91108. this._enableInteractionOnController(controller);
  91109. }
  91110. controller._interactionsEnabled = true;
  91111. controller._teleportationEnabled = true;
  91112. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91113. controller._dpadPressed = false;
  91114. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  91115. controller._dpadPressed = stateObject.pressed;
  91116. if (!controller._dpadPressed) {
  91117. controller._rotationLeftAsked = false;
  91118. controller._rotationRightAsked = false;
  91119. controller._teleportationBackRequestInitiated = false;
  91120. }
  91121. });
  91122. }
  91123. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  91124. if (_this.teleportationEnabled) {
  91125. _this._checkTeleportBackwards(stateObject, controller);
  91126. _this._checkTeleportWithRay(stateObject, controller);
  91127. }
  91128. _this._checkRotate(stateObject, controller);
  91129. });
  91130. }
  91131. };
  91132. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  91133. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  91134. this._teleportationTarget.isPickable = false;
  91135. var length = 512;
  91136. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  91137. dynamicTexture.hasAlpha = true;
  91138. var context = dynamicTexture.getContext();
  91139. var centerX = length / 2;
  91140. var centerY = length / 2;
  91141. var radius = 200;
  91142. context.beginPath();
  91143. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  91144. context.fillStyle = this._teleportationFillColor;
  91145. context.fill();
  91146. context.lineWidth = 10;
  91147. context.strokeStyle = this._teleportationBorderColor;
  91148. context.stroke();
  91149. context.closePath();
  91150. dynamicTexture.update();
  91151. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  91152. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  91153. this._teleportationTarget.material = teleportationCircleMaterial;
  91154. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  91155. torus.isPickable = false;
  91156. torus.parent = this._teleportationTarget;
  91157. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  91158. var keys = [];
  91159. keys.push({
  91160. frame: 0,
  91161. value: 0
  91162. });
  91163. keys.push({
  91164. frame: 30,
  91165. value: 0.4
  91166. });
  91167. keys.push({
  91168. frame: 60,
  91169. value: 0
  91170. });
  91171. animationInnerCircle.setKeys(keys);
  91172. var easingFunction = new BABYLON.SineEase();
  91173. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91174. animationInnerCircle.setEasingFunction(easingFunction);
  91175. torus.animations = [];
  91176. torus.animations.push(animationInnerCircle);
  91177. this._scene.beginAnimation(torus, 0, 60, true);
  91178. this._hideTeleportationTarget();
  91179. };
  91180. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  91181. this._teleportActive = true;
  91182. if (this._teleportationInitialized) {
  91183. this._teleportationTarget.isVisible = true;
  91184. if (this._isDefaultTeleportationTarget) {
  91185. this._teleportationTarget.getChildren()[0].isVisible = true;
  91186. }
  91187. }
  91188. };
  91189. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  91190. this._teleportActive = false;
  91191. if (this._teleportationInitialized) {
  91192. this._teleportationTarget.isVisible = false;
  91193. if (this._isDefaultTeleportationTarget) {
  91194. this._teleportationTarget.getChildren()[0].isVisible = false;
  91195. }
  91196. }
  91197. };
  91198. VRExperienceHelper.prototype._rotateCamera = function (right) {
  91199. var _this = this;
  91200. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91201. return;
  91202. }
  91203. if (right) {
  91204. this._rotationAngle++;
  91205. }
  91206. else {
  91207. this._rotationAngle--;
  91208. }
  91209. this.currentVRCamera.animations = [];
  91210. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  91211. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91212. var animationRotationKeys = [];
  91213. animationRotationKeys.push({
  91214. frame: 0,
  91215. value: this.currentVRCamera.rotationQuaternion
  91216. });
  91217. animationRotationKeys.push({
  91218. frame: 6,
  91219. value: target
  91220. });
  91221. animationRotation.setKeys(animationRotationKeys);
  91222. animationRotation.setEasingFunction(this._circleEase);
  91223. this.currentVRCamera.animations.push(animationRotation);
  91224. this._postProcessMove.animations = [];
  91225. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91226. var vignetteWeightKeys = [];
  91227. vignetteWeightKeys.push({
  91228. frame: 0,
  91229. value: 0
  91230. });
  91231. vignetteWeightKeys.push({
  91232. frame: 3,
  91233. value: 4
  91234. });
  91235. vignetteWeightKeys.push({
  91236. frame: 6,
  91237. value: 0
  91238. });
  91239. animationPP.setKeys(vignetteWeightKeys);
  91240. animationPP.setEasingFunction(this._circleEase);
  91241. this._postProcessMove.animations.push(animationPP);
  91242. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91243. var vignetteStretchKeys = [];
  91244. vignetteStretchKeys.push({
  91245. frame: 0,
  91246. value: 0
  91247. });
  91248. vignetteStretchKeys.push({
  91249. frame: 3,
  91250. value: 10
  91251. });
  91252. vignetteStretchKeys.push({
  91253. frame: 6,
  91254. value: 0
  91255. });
  91256. animationPP2.setKeys(vignetteStretchKeys);
  91257. animationPP2.setEasingFunction(this._circleEase);
  91258. this._postProcessMove.animations.push(animationPP2);
  91259. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91260. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91261. this._postProcessMove.samples = 4;
  91262. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91263. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  91264. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91265. });
  91266. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  91267. };
  91268. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  91269. if (hit.pickedPoint) {
  91270. if (gazer._teleportationRequestInitiated) {
  91271. this._displayTeleportationTarget();
  91272. this._haloCenter.copyFrom(hit.pickedPoint);
  91273. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  91274. }
  91275. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  91276. if (pickNormal) {
  91277. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91278. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91279. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  91280. }
  91281. this._teleportationTarget.position.y += 0.1;
  91282. }
  91283. };
  91284. VRExperienceHelper.prototype._teleportCamera = function (location) {
  91285. var _this = this;
  91286. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91287. return;
  91288. }
  91289. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  91290. // offset of the headset from the anchor.
  91291. if (this.webVRCamera.leftCamera) {
  91292. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  91293. this._workingVector.subtractInPlace(this.webVRCamera.position);
  91294. location.subtractToRef(this._workingVector, this._workingVector);
  91295. }
  91296. else {
  91297. this._workingVector.copyFrom(location);
  91298. }
  91299. // Add height to account for user's height offset
  91300. if (this.isInVRMode) {
  91301. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  91302. }
  91303. else {
  91304. this._workingVector.y += this._defaultHeight;
  91305. }
  91306. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  91307. // Create animation from the camera's position to the new location
  91308. this.currentVRCamera.animations = [];
  91309. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91310. var animationCameraTeleportationKeys = [{
  91311. frame: 0,
  91312. value: this.currentVRCamera.position
  91313. },
  91314. {
  91315. frame: 11,
  91316. value: this._workingVector
  91317. }
  91318. ];
  91319. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  91320. animationCameraTeleportation.setEasingFunction(this._circleEase);
  91321. this.currentVRCamera.animations.push(animationCameraTeleportation);
  91322. this._postProcessMove.animations = [];
  91323. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91324. var vignetteWeightKeys = [];
  91325. vignetteWeightKeys.push({
  91326. frame: 0,
  91327. value: 0
  91328. });
  91329. vignetteWeightKeys.push({
  91330. frame: 5,
  91331. value: 8
  91332. });
  91333. vignetteWeightKeys.push({
  91334. frame: 11,
  91335. value: 0
  91336. });
  91337. animationPP.setKeys(vignetteWeightKeys);
  91338. this._postProcessMove.animations.push(animationPP);
  91339. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91340. var vignetteStretchKeys = [];
  91341. vignetteStretchKeys.push({
  91342. frame: 0,
  91343. value: 0
  91344. });
  91345. vignetteStretchKeys.push({
  91346. frame: 5,
  91347. value: 10
  91348. });
  91349. vignetteStretchKeys.push({
  91350. frame: 11,
  91351. value: 0
  91352. });
  91353. animationPP2.setKeys(vignetteStretchKeys);
  91354. this._postProcessMove.animations.push(animationPP2);
  91355. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91356. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91357. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91358. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  91359. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91360. });
  91361. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  91362. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  91363. });
  91364. this._hideTeleportationTarget();
  91365. };
  91366. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  91367. if (normal) {
  91368. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  91369. if (angle < Math.PI / 2) {
  91370. normal.scaleInPlace(-1);
  91371. }
  91372. }
  91373. return normal;
  91374. };
  91375. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  91376. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91377. return;
  91378. }
  91379. var ray = gazer._getForwardRay(this._rayLength);
  91380. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91381. if (hit) {
  91382. // Populate the contrllers mesh that can be used for drag/drop
  91383. if (gazer._laserPointer) {
  91384. hit.originMesh = gazer._laserPointer.parent;
  91385. }
  91386. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  91387. }
  91388. gazer._currentHit = hit;
  91389. // Moving the gazeTracker on the mesh face targetted
  91390. if (hit && hit.pickedPoint) {
  91391. if (this._displayGaze) {
  91392. var multiplier = 1;
  91393. gazer._gazeTracker.isVisible = true;
  91394. if (gazer._isActionableMesh) {
  91395. multiplier = 3;
  91396. }
  91397. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  91398. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  91399. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  91400. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  91401. // To avoid z-fighting
  91402. var deltaFighting = 0.002;
  91403. if (pickNormal) {
  91404. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91405. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91406. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  91407. }
  91408. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  91409. if (gazer._gazeTracker.position.x < 0) {
  91410. gazer._gazeTracker.position.x += deltaFighting;
  91411. }
  91412. else {
  91413. gazer._gazeTracker.position.x -= deltaFighting;
  91414. }
  91415. if (gazer._gazeTracker.position.y < 0) {
  91416. gazer._gazeTracker.position.y += deltaFighting;
  91417. }
  91418. else {
  91419. gazer._gazeTracker.position.y -= deltaFighting;
  91420. }
  91421. if (gazer._gazeTracker.position.z < 0) {
  91422. gazer._gazeTracker.position.z += deltaFighting;
  91423. }
  91424. else {
  91425. gazer._gazeTracker.position.z -= deltaFighting;
  91426. }
  91427. }
  91428. // Changing the size of the laser pointer based on the distance from the targetted point
  91429. gazer._updatePointerDistance(hit.distance);
  91430. }
  91431. else {
  91432. gazer._updatePointerDistance();
  91433. gazer._gazeTracker.isVisible = false;
  91434. }
  91435. if (hit && hit.pickedMesh) {
  91436. // The object selected is the floor, we're in a teleportation scenario
  91437. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  91438. // Moving the teleportation area to this targetted point
  91439. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  91440. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  91441. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91442. }
  91443. gazer._currentMeshSelected = null;
  91444. if (gazer._teleportationRequestInitiated) {
  91445. this._moveTeleportationSelectorTo(hit, gazer, ray);
  91446. }
  91447. return;
  91448. }
  91449. // If not, we're in a selection scenario
  91450. //this._teleportationAllowed = false;
  91451. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  91452. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  91453. this.onNewMeshPicked.notifyObservers(hit);
  91454. gazer._currentMeshSelected = hit.pickedMesh;
  91455. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  91456. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  91457. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  91458. gazer._isActionableMesh = true;
  91459. }
  91460. else {
  91461. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91462. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91463. gazer._isActionableMesh = false;
  91464. }
  91465. try {
  91466. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  91467. }
  91468. catch (err) {
  91469. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  91470. }
  91471. }
  91472. else {
  91473. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91474. gazer._currentMeshSelected = null;
  91475. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91476. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91477. }
  91478. }
  91479. }
  91480. else {
  91481. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91482. gazer._currentMeshSelected = null;
  91483. //this._teleportationAllowed = false;
  91484. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91485. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91486. }
  91487. };
  91488. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  91489. if (mesh) {
  91490. this.onSelectedMeshUnselected.notifyObservers(mesh);
  91491. }
  91492. };
  91493. /**
  91494. * Sets the color of the laser ray from the vr controllers.
  91495. * @param color new color for the ray.
  91496. */
  91497. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  91498. if (this.leftController) {
  91499. this.leftController._setLaserPointerColor(color);
  91500. }
  91501. if (this.rightController) {
  91502. this.rightController._setLaserPointerColor(color);
  91503. }
  91504. };
  91505. /**
  91506. * Sets the color of the ray from the vr headsets gaze.
  91507. * @param color new color for the ray.
  91508. */
  91509. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  91510. if (!this._cameraGazer._gazeTracker.material) {
  91511. return;
  91512. }
  91513. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  91514. if (this.leftController) {
  91515. this.leftController._gazeTracker.material.emissiveColor = color;
  91516. }
  91517. if (this.rightController) {
  91518. this.rightController._gazeTracker.material.emissiveColor = color;
  91519. }
  91520. };
  91521. /**
  91522. * Exits VR and disposes of the vr experience helper
  91523. */
  91524. VRExperienceHelper.prototype.dispose = function () {
  91525. if (this.isInVRMode) {
  91526. this.exitVR();
  91527. }
  91528. if (this._postProcessMove) {
  91529. this._postProcessMove.dispose();
  91530. }
  91531. if (this._webVRCamera) {
  91532. this._webVRCamera.dispose();
  91533. }
  91534. if (this._vrDeviceOrientationCamera) {
  91535. this._vrDeviceOrientationCamera.dispose();
  91536. }
  91537. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  91538. document.body.removeChild(this._btnVR);
  91539. }
  91540. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  91541. this._deviceOrientationCamera.dispose();
  91542. }
  91543. if (this._cameraGazer) {
  91544. this._cameraGazer.dispose();
  91545. }
  91546. if (this.leftController) {
  91547. this.leftController.dispose();
  91548. }
  91549. if (this.rightController) {
  91550. this.rightController.dispose();
  91551. }
  91552. if (this._teleportationTarget) {
  91553. this._teleportationTarget.dispose();
  91554. }
  91555. this._floorMeshesCollection = [];
  91556. document.removeEventListener("keydown", this._onKeyDown);
  91557. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91558. window.removeEventListener("resize", this._onResize);
  91559. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  91560. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  91561. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  91562. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  91563. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  91564. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  91565. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  91566. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91567. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  91568. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  91569. this._scene.unregisterBeforeRender(this.beforeRender);
  91570. };
  91571. /**
  91572. * Gets the name of the VRExperienceHelper class
  91573. * @returns "VRExperienceHelper"
  91574. */
  91575. VRExperienceHelper.prototype.getClassName = function () {
  91576. return "VRExperienceHelper";
  91577. };
  91578. return VRExperienceHelper;
  91579. }());
  91580. BABYLON.VRExperienceHelper = VRExperienceHelper;
  91581. })(BABYLON || (BABYLON = {}));
  91582. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  91583. // Mainly based on these 2 articles :
  91584. // 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
  91585. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  91586. var BABYLON;
  91587. (function (BABYLON) {
  91588. /**
  91589. * Defines the potential axis of a Joystick
  91590. */
  91591. var JoystickAxis;
  91592. (function (JoystickAxis) {
  91593. /** X axis */
  91594. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  91595. /** Y axis */
  91596. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  91597. /** Z axis */
  91598. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  91599. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  91600. /**
  91601. * Class used to define virtual joystick (used in touch mode)
  91602. */
  91603. var VirtualJoystick = /** @class */ (function () {
  91604. /**
  91605. * Creates a new virtual joystick
  91606. * @param leftJoystick defines that the joystick is for left hand (false by default)
  91607. */
  91608. function VirtualJoystick(leftJoystick) {
  91609. var _this = this;
  91610. if (leftJoystick) {
  91611. this._leftJoystick = true;
  91612. }
  91613. else {
  91614. this._leftJoystick = false;
  91615. }
  91616. VirtualJoystick._globalJoystickIndex++;
  91617. // By default left & right arrow keys are moving the X
  91618. // and up & down keys are moving the Y
  91619. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91620. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91621. this.reverseLeftRight = false;
  91622. this.reverseUpDown = false;
  91623. // collections of pointers
  91624. this._touches = new BABYLON.StringDictionary();
  91625. this.deltaPosition = BABYLON.Vector3.Zero();
  91626. this._joystickSensibility = 25;
  91627. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91628. this._onResize = function (evt) {
  91629. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91630. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91631. if (VirtualJoystick.vjCanvas) {
  91632. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  91633. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  91634. }
  91635. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  91636. };
  91637. // injecting a canvas element on top of the canvas 3D game
  91638. if (!VirtualJoystick.vjCanvas) {
  91639. window.addEventListener("resize", this._onResize, false);
  91640. VirtualJoystick.vjCanvas = document.createElement("canvas");
  91641. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91642. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91643. VirtualJoystick.vjCanvas.width = window.innerWidth;
  91644. VirtualJoystick.vjCanvas.height = window.innerHeight;
  91645. VirtualJoystick.vjCanvas.style.width = "100%";
  91646. VirtualJoystick.vjCanvas.style.height = "100%";
  91647. VirtualJoystick.vjCanvas.style.position = "absolute";
  91648. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  91649. VirtualJoystick.vjCanvas.style.top = "0px";
  91650. VirtualJoystick.vjCanvas.style.left = "0px";
  91651. VirtualJoystick.vjCanvas.style.zIndex = "5";
  91652. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  91653. // Support for jQuery PEP polyfill
  91654. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  91655. var context = VirtualJoystick.vjCanvas.getContext('2d');
  91656. if (!context) {
  91657. throw new Error("Unable to create canvas for virtual joystick");
  91658. }
  91659. VirtualJoystick.vjCanvasContext = context;
  91660. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  91661. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91662. document.body.appendChild(VirtualJoystick.vjCanvas);
  91663. }
  91664. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  91665. this.pressed = false;
  91666. // default joystick color
  91667. this._joystickColor = "cyan";
  91668. this._joystickPointerID = -1;
  91669. // current joystick position
  91670. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  91671. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  91672. // origin joystick position
  91673. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  91674. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  91675. this._onPointerDownHandlerRef = function (evt) {
  91676. _this._onPointerDown(evt);
  91677. };
  91678. this._onPointerMoveHandlerRef = function (evt) {
  91679. _this._onPointerMove(evt);
  91680. };
  91681. this._onPointerUpHandlerRef = function (evt) {
  91682. _this._onPointerUp(evt);
  91683. };
  91684. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  91685. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  91686. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  91687. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  91688. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  91689. evt.preventDefault(); // Disables system menu
  91690. }, false);
  91691. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91692. }
  91693. /**
  91694. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  91695. * @param newJoystickSensibility defines the new sensibility
  91696. */
  91697. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  91698. this._joystickSensibility = newJoystickSensibility;
  91699. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91700. };
  91701. VirtualJoystick.prototype._onPointerDown = function (e) {
  91702. var positionOnScreenCondition;
  91703. e.preventDefault();
  91704. if (this._leftJoystick === true) {
  91705. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  91706. }
  91707. else {
  91708. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  91709. }
  91710. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  91711. // First contact will be dedicated to the virtual joystick
  91712. this._joystickPointerID = e.pointerId;
  91713. this._joystickPointerStartPos.x = e.clientX;
  91714. this._joystickPointerStartPos.y = e.clientY;
  91715. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  91716. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  91717. this._deltaJoystickVector.x = 0;
  91718. this._deltaJoystickVector.y = 0;
  91719. this.pressed = true;
  91720. this._touches.add(e.pointerId.toString(), e);
  91721. }
  91722. else {
  91723. // You can only trigger the action buttons with a joystick declared
  91724. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  91725. this._action();
  91726. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  91727. }
  91728. }
  91729. };
  91730. VirtualJoystick.prototype._onPointerMove = function (e) {
  91731. // If the current pointer is the one associated to the joystick (first touch contact)
  91732. if (this._joystickPointerID == e.pointerId) {
  91733. this._joystickPointerPos.x = e.clientX;
  91734. this._joystickPointerPos.y = e.clientY;
  91735. this._deltaJoystickVector = this._joystickPointerPos.clone();
  91736. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  91737. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  91738. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  91739. switch (this._axisTargetedByLeftAndRight) {
  91740. case JoystickAxis.X:
  91741. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  91742. break;
  91743. case JoystickAxis.Y:
  91744. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  91745. break;
  91746. case JoystickAxis.Z:
  91747. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  91748. break;
  91749. }
  91750. var directionUpDown = this.reverseUpDown ? 1 : -1;
  91751. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  91752. switch (this._axisTargetedByUpAndDown) {
  91753. case JoystickAxis.X:
  91754. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  91755. break;
  91756. case JoystickAxis.Y:
  91757. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  91758. break;
  91759. case JoystickAxis.Z:
  91760. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  91761. break;
  91762. }
  91763. }
  91764. else {
  91765. var data = this._touches.get(e.pointerId.toString());
  91766. if (data) {
  91767. data.x = e.clientX;
  91768. data.y = e.clientY;
  91769. }
  91770. }
  91771. };
  91772. VirtualJoystick.prototype._onPointerUp = function (e) {
  91773. if (this._joystickPointerID == e.pointerId) {
  91774. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  91775. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  91776. this._joystickPointerID = -1;
  91777. this.pressed = false;
  91778. }
  91779. else {
  91780. var touch = this._touches.get(e.pointerId.toString());
  91781. if (touch) {
  91782. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91783. }
  91784. }
  91785. this._deltaJoystickVector.x = 0;
  91786. this._deltaJoystickVector.y = 0;
  91787. this._touches.remove(e.pointerId.toString());
  91788. };
  91789. /**
  91790. * Change the color of the virtual joystick
  91791. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  91792. */
  91793. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  91794. this._joystickColor = newColor;
  91795. };
  91796. /**
  91797. * Defines a callback to call when the joystick is touched
  91798. * @param action defines the callback
  91799. */
  91800. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  91801. this._action = action;
  91802. };
  91803. /**
  91804. * Defines which axis you'd like to control for left & right
  91805. * @param axis defines the axis to use
  91806. */
  91807. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  91808. switch (axis) {
  91809. case JoystickAxis.X:
  91810. case JoystickAxis.Y:
  91811. case JoystickAxis.Z:
  91812. this._axisTargetedByLeftAndRight = axis;
  91813. break;
  91814. default:
  91815. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91816. break;
  91817. }
  91818. };
  91819. /**
  91820. * Defines which axis you'd like to control for up & down
  91821. * @param axis defines the axis to use
  91822. */
  91823. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  91824. switch (axis) {
  91825. case JoystickAxis.X:
  91826. case JoystickAxis.Y:
  91827. case JoystickAxis.Z:
  91828. this._axisTargetedByUpAndDown = axis;
  91829. break;
  91830. default:
  91831. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91832. break;
  91833. }
  91834. };
  91835. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  91836. var _this = this;
  91837. if (this.pressed) {
  91838. this._touches.forEach(function (key, touch) {
  91839. if (touch.pointerId === _this._joystickPointerID) {
  91840. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  91841. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  91842. VirtualJoystick.vjCanvasContext.beginPath();
  91843. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91844. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91845. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  91846. VirtualJoystick.vjCanvasContext.stroke();
  91847. VirtualJoystick.vjCanvasContext.closePath();
  91848. VirtualJoystick.vjCanvasContext.beginPath();
  91849. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91850. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91851. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  91852. VirtualJoystick.vjCanvasContext.stroke();
  91853. VirtualJoystick.vjCanvasContext.closePath();
  91854. VirtualJoystick.vjCanvasContext.beginPath();
  91855. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91856. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  91857. VirtualJoystick.vjCanvasContext.stroke();
  91858. VirtualJoystick.vjCanvasContext.closePath();
  91859. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  91860. }
  91861. else {
  91862. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91863. VirtualJoystick.vjCanvasContext.beginPath();
  91864. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  91865. VirtualJoystick.vjCanvasContext.beginPath();
  91866. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  91867. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91868. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  91869. VirtualJoystick.vjCanvasContext.stroke();
  91870. VirtualJoystick.vjCanvasContext.closePath();
  91871. touch.prevX = touch.x;
  91872. touch.prevY = touch.y;
  91873. }
  91874. ;
  91875. });
  91876. }
  91877. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91878. };
  91879. /**
  91880. * Release internal HTML canvas
  91881. */
  91882. VirtualJoystick.prototype.releaseCanvas = function () {
  91883. if (VirtualJoystick.vjCanvas) {
  91884. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  91885. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  91886. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  91887. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  91888. window.removeEventListener("resize", this._onResize);
  91889. document.body.removeChild(VirtualJoystick.vjCanvas);
  91890. VirtualJoystick.vjCanvas = null;
  91891. }
  91892. };
  91893. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  91894. VirtualJoystick._globalJoystickIndex = 0;
  91895. return VirtualJoystick;
  91896. }());
  91897. BABYLON.VirtualJoystick = VirtualJoystick;
  91898. })(BABYLON || (BABYLON = {}));
  91899. //# sourceMappingURL=babylon.virtualJoystick.js.map
  91900. var BABYLON;
  91901. (function (BABYLON) {
  91902. // We're mainly based on the logic defined into the FreeCamera code
  91903. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  91904. __extends(VirtualJoysticksCamera, _super);
  91905. function VirtualJoysticksCamera(name, position, scene) {
  91906. var _this = _super.call(this, name, position, scene) || this;
  91907. _this.inputs.addVirtualJoystick();
  91908. return _this;
  91909. }
  91910. VirtualJoysticksCamera.prototype.getClassName = function () {
  91911. return "VirtualJoysticksCamera";
  91912. };
  91913. return VirtualJoysticksCamera;
  91914. }(BABYLON.FreeCamera));
  91915. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  91916. })(BABYLON || (BABYLON = {}));
  91917. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  91918. var BABYLON;
  91919. (function (BABYLON) {
  91920. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  91921. function FreeCameraVirtualJoystickInput() {
  91922. }
  91923. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  91924. return this._leftjoystick;
  91925. };
  91926. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  91927. return this._rightjoystick;
  91928. };
  91929. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  91930. if (this._leftjoystick) {
  91931. var camera = this.camera;
  91932. var speed = camera._computeLocalCameraSpeed() * 50;
  91933. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  91934. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  91935. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  91936. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  91937. if (!this._leftjoystick.pressed) {
  91938. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  91939. }
  91940. if (!this._rightjoystick.pressed) {
  91941. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  91942. }
  91943. }
  91944. };
  91945. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  91946. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  91947. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  91948. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  91949. this._leftjoystick.setJoystickSensibility(0.15);
  91950. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  91951. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  91952. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  91953. this._rightjoystick.reverseUpDown = true;
  91954. this._rightjoystick.setJoystickSensibility(0.05);
  91955. this._rightjoystick.setJoystickColor("yellow");
  91956. };
  91957. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  91958. this._leftjoystick.releaseCanvas();
  91959. this._rightjoystick.releaseCanvas();
  91960. };
  91961. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  91962. return "FreeCameraVirtualJoystickInput";
  91963. };
  91964. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  91965. return "virtualJoystick";
  91966. };
  91967. return FreeCameraVirtualJoystickInput;
  91968. }());
  91969. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  91970. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  91971. })(BABYLON || (BABYLON = {}));
  91972. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  91973. var BABYLON;
  91974. (function (BABYLON) {
  91975. var SimplificationSettings = /** @class */ (function () {
  91976. function SimplificationSettings(quality, distance, optimizeMesh) {
  91977. this.quality = quality;
  91978. this.distance = distance;
  91979. this.optimizeMesh = optimizeMesh;
  91980. }
  91981. return SimplificationSettings;
  91982. }());
  91983. BABYLON.SimplificationSettings = SimplificationSettings;
  91984. var SimplificationQueue = /** @class */ (function () {
  91985. function SimplificationQueue() {
  91986. this.running = false;
  91987. this._simplificationArray = [];
  91988. }
  91989. SimplificationQueue.prototype.addTask = function (task) {
  91990. this._simplificationArray.push(task);
  91991. };
  91992. SimplificationQueue.prototype.executeNext = function () {
  91993. var task = this._simplificationArray.pop();
  91994. if (task) {
  91995. this.running = true;
  91996. this.runSimplification(task);
  91997. }
  91998. else {
  91999. this.running = false;
  92000. }
  92001. };
  92002. SimplificationQueue.prototype.runSimplification = function (task) {
  92003. var _this = this;
  92004. if (task.parallelProcessing) {
  92005. //parallel simplifier
  92006. task.settings.forEach(function (setting) {
  92007. var simplifier = _this.getSimplifier(task);
  92008. simplifier.simplify(setting, function (newMesh) {
  92009. task.mesh.addLODLevel(setting.distance, newMesh);
  92010. newMesh.isVisible = true;
  92011. //check if it is the last
  92012. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  92013. //all done, run the success callback.
  92014. task.successCallback();
  92015. }
  92016. _this.executeNext();
  92017. });
  92018. });
  92019. }
  92020. else {
  92021. //single simplifier.
  92022. var simplifier = this.getSimplifier(task);
  92023. var runDecimation = function (setting, callback) {
  92024. simplifier.simplify(setting, function (newMesh) {
  92025. task.mesh.addLODLevel(setting.distance, newMesh);
  92026. newMesh.isVisible = true;
  92027. //run the next quality level
  92028. callback();
  92029. });
  92030. };
  92031. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  92032. runDecimation(task.settings[loop.index], function () {
  92033. loop.executeNext();
  92034. });
  92035. }, function () {
  92036. //execution ended, run the success callback.
  92037. if (task.successCallback) {
  92038. task.successCallback();
  92039. }
  92040. _this.executeNext();
  92041. });
  92042. }
  92043. };
  92044. SimplificationQueue.prototype.getSimplifier = function (task) {
  92045. switch (task.simplificationType) {
  92046. case SimplificationType.QUADRATIC:
  92047. default:
  92048. return new QuadraticErrorSimplification(task.mesh);
  92049. }
  92050. };
  92051. return SimplificationQueue;
  92052. }());
  92053. BABYLON.SimplificationQueue = SimplificationQueue;
  92054. /**
  92055. * The implemented types of simplification
  92056. * At the moment only Quadratic Error Decimation is implemented
  92057. */
  92058. var SimplificationType;
  92059. (function (SimplificationType) {
  92060. /** Quadratic error decimation */
  92061. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  92062. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  92063. var DecimationTriangle = /** @class */ (function () {
  92064. function DecimationTriangle(vertices) {
  92065. this.vertices = vertices;
  92066. this.error = new Array(4);
  92067. this.deleted = false;
  92068. this.isDirty = false;
  92069. this.deletePending = false;
  92070. this.borderFactor = 0;
  92071. }
  92072. return DecimationTriangle;
  92073. }());
  92074. BABYLON.DecimationTriangle = DecimationTriangle;
  92075. var DecimationVertex = /** @class */ (function () {
  92076. function DecimationVertex(position, id) {
  92077. this.position = position;
  92078. this.id = id;
  92079. this.isBorder = true;
  92080. this.q = new QuadraticMatrix();
  92081. this.triangleCount = 0;
  92082. this.triangleStart = 0;
  92083. this.originalOffsets = [];
  92084. }
  92085. DecimationVertex.prototype.updatePosition = function (newPosition) {
  92086. this.position.copyFrom(newPosition);
  92087. };
  92088. return DecimationVertex;
  92089. }());
  92090. BABYLON.DecimationVertex = DecimationVertex;
  92091. var QuadraticMatrix = /** @class */ (function () {
  92092. function QuadraticMatrix(data) {
  92093. this.data = new Array(10);
  92094. for (var i = 0; i < 10; ++i) {
  92095. if (data && data[i]) {
  92096. this.data[i] = data[i];
  92097. }
  92098. else {
  92099. this.data[i] = 0;
  92100. }
  92101. }
  92102. }
  92103. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  92104. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  92105. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  92106. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  92107. return det;
  92108. };
  92109. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  92110. for (var i = 0; i < 10; ++i) {
  92111. this.data[i] += matrix.data[i];
  92112. }
  92113. };
  92114. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  92115. for (var i = 0; i < 10; ++i) {
  92116. this.data[i] += data[i];
  92117. }
  92118. };
  92119. QuadraticMatrix.prototype.add = function (matrix) {
  92120. var m = new QuadraticMatrix();
  92121. for (var i = 0; i < 10; ++i) {
  92122. m.data[i] = this.data[i] + matrix.data[i];
  92123. }
  92124. return m;
  92125. };
  92126. QuadraticMatrix.FromData = function (a, b, c, d) {
  92127. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  92128. };
  92129. //returning an array to avoid garbage collection
  92130. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  92131. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  92132. };
  92133. return QuadraticMatrix;
  92134. }());
  92135. BABYLON.QuadraticMatrix = QuadraticMatrix;
  92136. var Reference = /** @class */ (function () {
  92137. function Reference(vertexId, triangleId) {
  92138. this.vertexId = vertexId;
  92139. this.triangleId = triangleId;
  92140. }
  92141. return Reference;
  92142. }());
  92143. BABYLON.Reference = Reference;
  92144. /**
  92145. * An implementation of the Quadratic Error simplification algorithm.
  92146. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  92147. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  92148. * @author RaananW
  92149. */
  92150. var QuadraticErrorSimplification = /** @class */ (function () {
  92151. function QuadraticErrorSimplification(_mesh) {
  92152. this._mesh = _mesh;
  92153. this.syncIterations = 5000;
  92154. this.aggressiveness = 7;
  92155. this.decimationIterations = 100;
  92156. this.boundingBoxEpsilon = BABYLON.Epsilon;
  92157. }
  92158. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  92159. var _this = this;
  92160. this.initDecimatedMesh();
  92161. //iterating through the submeshes array, one after the other.
  92162. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  92163. _this.initWithMesh(loop.index, function () {
  92164. _this.runDecimation(settings, loop.index, function () {
  92165. loop.executeNext();
  92166. });
  92167. }, settings.optimizeMesh);
  92168. }, function () {
  92169. setTimeout(function () {
  92170. successCallback(_this._reconstructedMesh);
  92171. }, 0);
  92172. });
  92173. };
  92174. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  92175. var _this = this;
  92176. var targetCount = ~~(this.triangles.length * settings.quality);
  92177. var deletedTriangles = 0;
  92178. var triangleCount = this.triangles.length;
  92179. var iterationFunction = function (iteration, callback) {
  92180. setTimeout(function () {
  92181. if (iteration % 5 === 0) {
  92182. _this.updateMesh(iteration === 0);
  92183. }
  92184. for (var i = 0; i < _this.triangles.length; ++i) {
  92185. _this.triangles[i].isDirty = false;
  92186. }
  92187. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  92188. var trianglesIterator = function (i) {
  92189. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  92190. var t = _this.triangles[tIdx];
  92191. if (!t)
  92192. return;
  92193. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  92194. return;
  92195. }
  92196. for (var j = 0; j < 3; ++j) {
  92197. if (t.error[j] < threshold) {
  92198. var deleted0 = [];
  92199. var deleted1 = [];
  92200. var v0 = t.vertices[j];
  92201. var v1 = t.vertices[(j + 1) % 3];
  92202. if (v0.isBorder || v1.isBorder)
  92203. continue;
  92204. var p = BABYLON.Vector3.Zero();
  92205. var n = BABYLON.Vector3.Zero();
  92206. var uv = BABYLON.Vector2.Zero();
  92207. var color = new BABYLON.Color4(0, 0, 0, 1);
  92208. _this.calculateError(v0, v1, p, n, uv, color);
  92209. var delTr = new Array();
  92210. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  92211. continue;
  92212. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  92213. continue;
  92214. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  92215. continue;
  92216. var uniqueArray = new Array();
  92217. delTr.forEach(function (deletedT) {
  92218. if (uniqueArray.indexOf(deletedT) === -1) {
  92219. deletedT.deletePending = true;
  92220. uniqueArray.push(deletedT);
  92221. }
  92222. });
  92223. if (uniqueArray.length % 2 !== 0) {
  92224. continue;
  92225. }
  92226. v0.q = v1.q.add(v0.q);
  92227. v0.updatePosition(p);
  92228. var tStart = _this.references.length;
  92229. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  92230. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  92231. var tCount = _this.references.length - tStart;
  92232. if (tCount <= v0.triangleCount) {
  92233. if (tCount) {
  92234. for (var c = 0; c < tCount; c++) {
  92235. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  92236. }
  92237. }
  92238. }
  92239. else {
  92240. v0.triangleStart = tStart;
  92241. }
  92242. v0.triangleCount = tCount;
  92243. break;
  92244. }
  92245. }
  92246. };
  92247. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  92248. }, 0);
  92249. };
  92250. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  92251. if (triangleCount - deletedTriangles <= targetCount)
  92252. loop.breakLoop();
  92253. else {
  92254. iterationFunction(loop.index, function () {
  92255. loop.executeNext();
  92256. });
  92257. }
  92258. }, function () {
  92259. setTimeout(function () {
  92260. //reconstruct this part of the mesh
  92261. _this.reconstructMesh(submeshIndex);
  92262. successCallback();
  92263. }, 0);
  92264. });
  92265. };
  92266. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  92267. var _this = this;
  92268. this.vertices = [];
  92269. this.triangles = [];
  92270. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  92271. var indices = this._mesh.getIndices();
  92272. var submesh = this._mesh.subMeshes[submeshIndex];
  92273. var findInVertices = function (positionToSearch) {
  92274. if (optimizeMesh) {
  92275. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  92276. if (_this.vertices[ii].position.equals(positionToSearch)) {
  92277. return _this.vertices[ii];
  92278. }
  92279. }
  92280. }
  92281. return null;
  92282. };
  92283. var vertexReferences = [];
  92284. var vertexInit = function (i) {
  92285. if (!positionData) {
  92286. return;
  92287. }
  92288. var offset = i + submesh.verticesStart;
  92289. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  92290. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  92291. vertex.originalOffsets.push(offset);
  92292. if (vertex.id === _this.vertices.length) {
  92293. _this.vertices.push(vertex);
  92294. }
  92295. vertexReferences.push(vertex.id);
  92296. };
  92297. //var totalVertices = mesh.getTotalVertices();
  92298. var totalVertices = submesh.verticesCount;
  92299. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  92300. var indicesInit = function (i) {
  92301. if (!indices) {
  92302. return;
  92303. }
  92304. var offset = (submesh.indexStart / 3) + i;
  92305. var pos = (offset * 3);
  92306. var i0 = indices[pos + 0];
  92307. var i1 = indices[pos + 1];
  92308. var i2 = indices[pos + 2];
  92309. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  92310. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  92311. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  92312. var triangle = new DecimationTriangle([v0, v1, v2]);
  92313. triangle.originalOffset = pos;
  92314. _this.triangles.push(triangle);
  92315. };
  92316. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  92317. _this.init(callback);
  92318. });
  92319. });
  92320. };
  92321. QuadraticErrorSimplification.prototype.init = function (callback) {
  92322. var _this = this;
  92323. var triangleInit1 = function (i) {
  92324. var t = _this.triangles[i];
  92325. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  92326. for (var j = 0; j < 3; j++) {
  92327. 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))));
  92328. }
  92329. };
  92330. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  92331. var triangleInit2 = function (i) {
  92332. var t = _this.triangles[i];
  92333. for (var j = 0; j < 3; ++j) {
  92334. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  92335. }
  92336. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92337. };
  92338. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  92339. callback();
  92340. });
  92341. });
  92342. };
  92343. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  92344. var newTriangles = [];
  92345. var i;
  92346. for (i = 0; i < this.vertices.length; ++i) {
  92347. this.vertices[i].triangleCount = 0;
  92348. }
  92349. var t;
  92350. var j;
  92351. for (i = 0; i < this.triangles.length; ++i) {
  92352. if (!this.triangles[i].deleted) {
  92353. t = this.triangles[i];
  92354. for (j = 0; j < 3; ++j) {
  92355. t.vertices[j].triangleCount = 1;
  92356. }
  92357. newTriangles.push(t);
  92358. }
  92359. }
  92360. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  92361. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  92362. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  92363. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  92364. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  92365. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  92366. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  92367. var vertexCount = 0;
  92368. for (i = 0; i < this.vertices.length; ++i) {
  92369. var vertex = this.vertices[i];
  92370. vertex.id = vertexCount;
  92371. if (vertex.triangleCount) {
  92372. vertex.originalOffsets.forEach(function (originalOffset) {
  92373. if (!normalData) {
  92374. return;
  92375. }
  92376. newPositionData.push(vertex.position.x);
  92377. newPositionData.push(vertex.position.y);
  92378. newPositionData.push(vertex.position.z);
  92379. newNormalData.push(normalData[originalOffset * 3]);
  92380. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  92381. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  92382. if (uvs && uvs.length) {
  92383. newUVsData.push(uvs[(originalOffset * 2)]);
  92384. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  92385. }
  92386. else if (colorsData && colorsData.length) {
  92387. newColorsData.push(colorsData[(originalOffset * 4)]);
  92388. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  92389. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  92390. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  92391. }
  92392. ++vertexCount;
  92393. });
  92394. }
  92395. }
  92396. var startingIndex = this._reconstructedMesh.getTotalIndices();
  92397. var startingVertex = this._reconstructedMesh.getTotalVertices();
  92398. var submeshesArray = this._reconstructedMesh.subMeshes;
  92399. this._reconstructedMesh.subMeshes = [];
  92400. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  92401. var originalIndices = this._mesh.getIndices();
  92402. for (i = 0; i < newTriangles.length; ++i) {
  92403. t = newTriangles[i]; //now get the new referencing point for each vertex
  92404. [0, 1, 2].forEach(function (idx) {
  92405. var id = originalIndices[t.originalOffset + idx];
  92406. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  92407. if (offset < 0)
  92408. offset = 0;
  92409. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  92410. });
  92411. }
  92412. //overwriting the old vertex buffers and indices.
  92413. this._reconstructedMesh.setIndices(newIndicesArray);
  92414. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  92415. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  92416. if (newUVsData.length > 0)
  92417. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  92418. if (newColorsData.length > 0)
  92419. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  92420. //create submesh
  92421. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  92422. if (submeshIndex > 0) {
  92423. this._reconstructedMesh.subMeshes = [];
  92424. submeshesArray.forEach(function (submesh) {
  92425. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  92426. });
  92427. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  92428. }
  92429. };
  92430. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  92431. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  92432. this._reconstructedMesh.material = this._mesh.material;
  92433. this._reconstructedMesh.parent = this._mesh.parent;
  92434. this._reconstructedMesh.isVisible = false;
  92435. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  92436. };
  92437. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  92438. for (var i = 0; i < vertex1.triangleCount; ++i) {
  92439. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  92440. if (t.deleted)
  92441. continue;
  92442. var s = this.references[vertex1.triangleStart + i].vertexId;
  92443. var v1 = t.vertices[(s + 1) % 3];
  92444. var v2 = t.vertices[(s + 2) % 3];
  92445. if ((v1 === vertex2 || v2 === vertex2)) {
  92446. deletedArray[i] = true;
  92447. delTr.push(t);
  92448. continue;
  92449. }
  92450. var d1 = v1.position.subtract(point);
  92451. d1 = d1.normalize();
  92452. var d2 = v2.position.subtract(point);
  92453. d2 = d2.normalize();
  92454. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  92455. return true;
  92456. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  92457. deletedArray[i] = false;
  92458. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  92459. return true;
  92460. }
  92461. return false;
  92462. };
  92463. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  92464. var newDeleted = deletedTriangles;
  92465. for (var i = 0; i < vertex.triangleCount; ++i) {
  92466. var ref = this.references[vertex.triangleStart + i];
  92467. var t = this.triangles[ref.triangleId];
  92468. if (t.deleted)
  92469. continue;
  92470. if (deletedArray[i] && t.deletePending) {
  92471. t.deleted = true;
  92472. newDeleted++;
  92473. continue;
  92474. }
  92475. t.vertices[ref.vertexId] = origVertex;
  92476. t.isDirty = true;
  92477. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  92478. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  92479. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  92480. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92481. this.references.push(ref);
  92482. }
  92483. return newDeleted;
  92484. };
  92485. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  92486. for (var i = 0; i < this.vertices.length; ++i) {
  92487. var vCount = [];
  92488. var vId = [];
  92489. var v = this.vertices[i];
  92490. var j;
  92491. for (j = 0; j < v.triangleCount; ++j) {
  92492. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  92493. for (var ii = 0; ii < 3; ii++) {
  92494. var ofs = 0;
  92495. var vv = triangle.vertices[ii];
  92496. while (ofs < vCount.length) {
  92497. if (vId[ofs] === vv.id)
  92498. break;
  92499. ++ofs;
  92500. }
  92501. if (ofs === vCount.length) {
  92502. vCount.push(1);
  92503. vId.push(vv.id);
  92504. }
  92505. else {
  92506. vCount[ofs]++;
  92507. }
  92508. }
  92509. }
  92510. for (j = 0; j < vCount.length; ++j) {
  92511. if (vCount[j] === 1) {
  92512. this.vertices[vId[j]].isBorder = true;
  92513. }
  92514. else {
  92515. this.vertices[vId[j]].isBorder = false;
  92516. }
  92517. }
  92518. }
  92519. };
  92520. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  92521. if (identifyBorders === void 0) { identifyBorders = false; }
  92522. var i;
  92523. if (!identifyBorders) {
  92524. var newTrianglesVector = [];
  92525. for (i = 0; i < this.triangles.length; ++i) {
  92526. if (!this.triangles[i].deleted) {
  92527. newTrianglesVector.push(this.triangles[i]);
  92528. }
  92529. }
  92530. this.triangles = newTrianglesVector;
  92531. }
  92532. for (i = 0; i < this.vertices.length; ++i) {
  92533. this.vertices[i].triangleCount = 0;
  92534. this.vertices[i].triangleStart = 0;
  92535. }
  92536. var t;
  92537. var j;
  92538. var v;
  92539. for (i = 0; i < this.triangles.length; ++i) {
  92540. t = this.triangles[i];
  92541. for (j = 0; j < 3; ++j) {
  92542. v = t.vertices[j];
  92543. v.triangleCount++;
  92544. }
  92545. }
  92546. var tStart = 0;
  92547. for (i = 0; i < this.vertices.length; ++i) {
  92548. this.vertices[i].triangleStart = tStart;
  92549. tStart += this.vertices[i].triangleCount;
  92550. this.vertices[i].triangleCount = 0;
  92551. }
  92552. var newReferences = new Array(this.triangles.length * 3);
  92553. for (i = 0; i < this.triangles.length; ++i) {
  92554. t = this.triangles[i];
  92555. for (j = 0; j < 3; ++j) {
  92556. v = t.vertices[j];
  92557. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  92558. v.triangleCount++;
  92559. }
  92560. }
  92561. this.references = newReferences;
  92562. if (identifyBorders) {
  92563. this.identifyBorder();
  92564. }
  92565. };
  92566. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  92567. var x = point.x;
  92568. var y = point.y;
  92569. var z = point.z;
  92570. 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
  92571. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  92572. };
  92573. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  92574. var q = vertex1.q.add(vertex2.q);
  92575. var border = vertex1.isBorder && vertex2.isBorder;
  92576. var error = 0;
  92577. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  92578. if (qDet !== 0 && !border) {
  92579. if (!pointResult) {
  92580. pointResult = BABYLON.Vector3.Zero();
  92581. }
  92582. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  92583. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  92584. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  92585. error = this.vertexError(q, pointResult);
  92586. }
  92587. else {
  92588. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  92589. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  92590. var error1 = this.vertexError(q, vertex1.position);
  92591. var error2 = this.vertexError(q, vertex2.position);
  92592. var error3 = this.vertexError(q, p3);
  92593. error = Math.min(error1, error2, error3);
  92594. if (error === error1) {
  92595. if (pointResult) {
  92596. pointResult.copyFrom(vertex1.position);
  92597. }
  92598. }
  92599. else if (error === error2) {
  92600. if (pointResult) {
  92601. pointResult.copyFrom(vertex2.position);
  92602. }
  92603. }
  92604. else {
  92605. if (pointResult) {
  92606. pointResult.copyFrom(p3);
  92607. }
  92608. }
  92609. }
  92610. return error;
  92611. };
  92612. return QuadraticErrorSimplification;
  92613. }());
  92614. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  92615. })(BABYLON || (BABYLON = {}));
  92616. //# sourceMappingURL=babylon.meshSimplification.js.map
  92617. var BABYLON;
  92618. (function (BABYLON) {
  92619. var MeshLODLevel = /** @class */ (function () {
  92620. function MeshLODLevel(distance, mesh) {
  92621. this.distance = distance;
  92622. this.mesh = mesh;
  92623. }
  92624. return MeshLODLevel;
  92625. }());
  92626. BABYLON.MeshLODLevel = MeshLODLevel;
  92627. })(BABYLON || (BABYLON = {}));
  92628. //# sourceMappingURL=babylon.meshLODLevel.js.map
  92629. var BABYLON;
  92630. (function (BABYLON) {
  92631. /**
  92632. * Defines the root class used to create scene optimization to use with SceneOptimizer
  92633. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92634. */
  92635. var SceneOptimization = /** @class */ (function () {
  92636. /**
  92637. * Creates the SceneOptimization object
  92638. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92639. * @param desc defines the description associated with the optimization
  92640. */
  92641. function SceneOptimization(
  92642. /**
  92643. * Defines the priority of this optimization (0 by default which means first in the list)
  92644. */
  92645. priority) {
  92646. if (priority === void 0) { priority = 0; }
  92647. this.priority = priority;
  92648. }
  92649. /**
  92650. * Gets a string describing the action executed by the current optimization
  92651. * @returns description string
  92652. */
  92653. SceneOptimization.prototype.getDescription = function () {
  92654. return "";
  92655. };
  92656. /**
  92657. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92658. * @param scene defines the current scene where to apply this optimization
  92659. * @param optimizer defines the current optimizer
  92660. * @returns true if everything that can be done was applied
  92661. */
  92662. SceneOptimization.prototype.apply = function (scene, optimizer) {
  92663. return true;
  92664. };
  92665. ;
  92666. return SceneOptimization;
  92667. }());
  92668. BABYLON.SceneOptimization = SceneOptimization;
  92669. /**
  92670. * Defines an optimization used to reduce the size of render target textures
  92671. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92672. */
  92673. var TextureOptimization = /** @class */ (function (_super) {
  92674. __extends(TextureOptimization, _super);
  92675. /**
  92676. * Creates the TextureOptimization object
  92677. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92678. * @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
  92679. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92680. */
  92681. function TextureOptimization(
  92682. /**
  92683. * Defines the priority of this optimization (0 by default which means first in the list)
  92684. */
  92685. priority,
  92686. /**
  92687. * 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
  92688. */
  92689. maximumSize,
  92690. /**
  92691. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92692. */
  92693. step) {
  92694. if (priority === void 0) { priority = 0; }
  92695. if (maximumSize === void 0) { maximumSize = 1024; }
  92696. if (step === void 0) { step = 0.5; }
  92697. var _this = _super.call(this, priority) || this;
  92698. _this.priority = priority;
  92699. _this.maximumSize = maximumSize;
  92700. _this.step = step;
  92701. return _this;
  92702. }
  92703. /**
  92704. * Gets a string describing the action executed by the current optimization
  92705. * @returns description string
  92706. */
  92707. TextureOptimization.prototype.getDescription = function () {
  92708. return "Reducing render target texture size to " + this.maximumSize;
  92709. };
  92710. /**
  92711. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92712. * @param scene defines the current scene where to apply this optimization
  92713. * @param optimizer defines the current optimizer
  92714. * @returns true if everything that can be done was applied
  92715. */
  92716. TextureOptimization.prototype.apply = function (scene, optimizer) {
  92717. var allDone = true;
  92718. for (var index = 0; index < scene.textures.length; index++) {
  92719. var texture = scene.textures[index];
  92720. if (!texture.canRescale || texture.getContext) {
  92721. continue;
  92722. }
  92723. var currentSize = texture.getSize();
  92724. var maxDimension = Math.max(currentSize.width, currentSize.height);
  92725. if (maxDimension > this.maximumSize) {
  92726. texture.scale(this.step);
  92727. allDone = false;
  92728. }
  92729. }
  92730. return allDone;
  92731. };
  92732. return TextureOptimization;
  92733. }(SceneOptimization));
  92734. BABYLON.TextureOptimization = TextureOptimization;
  92735. /**
  92736. * Defines an optimization used to increase or decrease the rendering resolution
  92737. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92738. */
  92739. var HardwareScalingOptimization = /** @class */ (function (_super) {
  92740. __extends(HardwareScalingOptimization, _super);
  92741. /**
  92742. * Creates the HardwareScalingOptimization object
  92743. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92744. * @param maximumScale defines the maximum scale to use (2 by default)
  92745. * @param step defines the step to use between two passes (0.5 by default)
  92746. */
  92747. function HardwareScalingOptimization(
  92748. /**
  92749. * Defines the priority of this optimization (0 by default which means first in the list)
  92750. */
  92751. priority,
  92752. /**
  92753. * Defines the maximum scale to use (2 by default)
  92754. */
  92755. maximumScale,
  92756. /**
  92757. * Defines the step to use between two passes (0.5 by default)
  92758. */
  92759. step) {
  92760. if (priority === void 0) { priority = 0; }
  92761. if (maximumScale === void 0) { maximumScale = 2; }
  92762. if (step === void 0) { step = 0.25; }
  92763. var _this = _super.call(this, priority) || this;
  92764. _this.priority = priority;
  92765. _this.maximumScale = maximumScale;
  92766. _this.step = step;
  92767. _this._currentScale = -1;
  92768. _this._directionOffset = 1;
  92769. return _this;
  92770. }
  92771. /**
  92772. * Gets a string describing the action executed by the current optimization
  92773. * @return description string
  92774. */
  92775. HardwareScalingOptimization.prototype.getDescription = function () {
  92776. return "Setting hardware scaling level to " + this._currentScale;
  92777. };
  92778. /**
  92779. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92780. * @param scene defines the current scene where to apply this optimization
  92781. * @param optimizer defines the current optimizer
  92782. * @returns true if everything that can be done was applied
  92783. */
  92784. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  92785. if (this._currentScale === -1) {
  92786. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  92787. if (this._currentScale > this.maximumScale) {
  92788. this._directionOffset = -1;
  92789. }
  92790. }
  92791. this._currentScale += this._directionOffset * this.step;
  92792. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  92793. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  92794. };
  92795. ;
  92796. return HardwareScalingOptimization;
  92797. }(SceneOptimization));
  92798. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  92799. /**
  92800. * Defines an optimization used to remove shadows
  92801. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92802. */
  92803. var ShadowsOptimization = /** @class */ (function (_super) {
  92804. __extends(ShadowsOptimization, _super);
  92805. function ShadowsOptimization() {
  92806. return _super !== null && _super.apply(this, arguments) || this;
  92807. }
  92808. /**
  92809. * Gets a string describing the action executed by the current optimization
  92810. * @return description string
  92811. */
  92812. ShadowsOptimization.prototype.getDescription = function () {
  92813. return "Turning shadows on/off";
  92814. };
  92815. /**
  92816. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92817. * @param scene defines the current scene where to apply this optimization
  92818. * @param optimizer defines the current optimizer
  92819. * @returns true if everything that can be done was applied
  92820. */
  92821. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  92822. scene.shadowsEnabled = optimizer.isInImprovementMode;
  92823. return true;
  92824. };
  92825. ;
  92826. return ShadowsOptimization;
  92827. }(SceneOptimization));
  92828. BABYLON.ShadowsOptimization = ShadowsOptimization;
  92829. /**
  92830. * Defines an optimization used to turn post-processes off
  92831. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92832. */
  92833. var PostProcessesOptimization = /** @class */ (function (_super) {
  92834. __extends(PostProcessesOptimization, _super);
  92835. function PostProcessesOptimization() {
  92836. return _super !== null && _super.apply(this, arguments) || this;
  92837. }
  92838. /**
  92839. * Gets a string describing the action executed by the current optimization
  92840. * @return description string
  92841. */
  92842. PostProcessesOptimization.prototype.getDescription = function () {
  92843. return "Turning post-processes on/off";
  92844. };
  92845. /**
  92846. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92847. * @param scene defines the current scene where to apply this optimization
  92848. * @param optimizer defines the current optimizer
  92849. * @returns true if everything that can be done was applied
  92850. */
  92851. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  92852. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  92853. return true;
  92854. };
  92855. ;
  92856. return PostProcessesOptimization;
  92857. }(SceneOptimization));
  92858. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  92859. /**
  92860. * Defines an optimization used to turn lens flares off
  92861. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92862. */
  92863. var LensFlaresOptimization = /** @class */ (function (_super) {
  92864. __extends(LensFlaresOptimization, _super);
  92865. function LensFlaresOptimization() {
  92866. return _super !== null && _super.apply(this, arguments) || this;
  92867. }
  92868. /**
  92869. * Gets a string describing the action executed by the current optimization
  92870. * @return description string
  92871. */
  92872. LensFlaresOptimization.prototype.getDescription = function () {
  92873. return "Turning lens flares on/off";
  92874. };
  92875. /**
  92876. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92877. * @param scene defines the current scene where to apply this optimization
  92878. * @param optimizer defines the current optimizer
  92879. * @returns true if everything that can be done was applied
  92880. */
  92881. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  92882. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  92883. return true;
  92884. };
  92885. ;
  92886. return LensFlaresOptimization;
  92887. }(SceneOptimization));
  92888. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  92889. /**
  92890. * Defines an optimization based on user defined callback.
  92891. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92892. */
  92893. var CustomOptimization = /** @class */ (function (_super) {
  92894. __extends(CustomOptimization, _super);
  92895. function CustomOptimization() {
  92896. return _super !== null && _super.apply(this, arguments) || this;
  92897. }
  92898. /**
  92899. * Gets a string describing the action executed by the current optimization
  92900. * @returns description string
  92901. */
  92902. CustomOptimization.prototype.getDescription = function () {
  92903. if (this.onGetDescription) {
  92904. return this.onGetDescription();
  92905. }
  92906. return "Running user defined callback";
  92907. };
  92908. /**
  92909. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92910. * @param scene defines the current scene where to apply this optimization
  92911. * @param optimizer defines the current optimizer
  92912. * @returns true if everything that can be done was applied
  92913. */
  92914. CustomOptimization.prototype.apply = function (scene, optimizer) {
  92915. if (this.onApply) {
  92916. return this.onApply(scene, optimizer);
  92917. }
  92918. return true;
  92919. };
  92920. ;
  92921. return CustomOptimization;
  92922. }(SceneOptimization));
  92923. BABYLON.CustomOptimization = CustomOptimization;
  92924. /**
  92925. * Defines an optimization used to turn particles off
  92926. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92927. */
  92928. var ParticlesOptimization = /** @class */ (function (_super) {
  92929. __extends(ParticlesOptimization, _super);
  92930. function ParticlesOptimization() {
  92931. return _super !== null && _super.apply(this, arguments) || this;
  92932. }
  92933. /**
  92934. * Gets a string describing the action executed by the current optimization
  92935. * @return description string
  92936. */
  92937. ParticlesOptimization.prototype.getDescription = function () {
  92938. return "Turning particles on/off";
  92939. };
  92940. /**
  92941. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92942. * @param scene defines the current scene where to apply this optimization
  92943. * @param optimizer defines the current optimizer
  92944. * @returns true if everything that can be done was applied
  92945. */
  92946. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  92947. scene.particlesEnabled = optimizer.isInImprovementMode;
  92948. return true;
  92949. };
  92950. ;
  92951. return ParticlesOptimization;
  92952. }(SceneOptimization));
  92953. BABYLON.ParticlesOptimization = ParticlesOptimization;
  92954. /**
  92955. * Defines an optimization used to turn render targets off
  92956. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92957. */
  92958. var RenderTargetsOptimization = /** @class */ (function (_super) {
  92959. __extends(RenderTargetsOptimization, _super);
  92960. function RenderTargetsOptimization() {
  92961. return _super !== null && _super.apply(this, arguments) || this;
  92962. }
  92963. /**
  92964. * Gets a string describing the action executed by the current optimization
  92965. * @return description string
  92966. */
  92967. RenderTargetsOptimization.prototype.getDescription = function () {
  92968. return "Turning render targets off";
  92969. };
  92970. /**
  92971. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92972. * @param scene defines the current scene where to apply this optimization
  92973. * @param optimizer defines the current optimizer
  92974. * @returns true if everything that can be done was applied
  92975. */
  92976. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  92977. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  92978. return true;
  92979. };
  92980. ;
  92981. return RenderTargetsOptimization;
  92982. }(SceneOptimization));
  92983. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  92984. /**
  92985. * Defines an optimization used to merge meshes with compatible materials
  92986. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92987. */
  92988. var MergeMeshesOptimization = /** @class */ (function (_super) {
  92989. __extends(MergeMeshesOptimization, _super);
  92990. function MergeMeshesOptimization() {
  92991. var _this = _super !== null && _super.apply(this, arguments) || this;
  92992. _this._canBeMerged = function (abstractMesh) {
  92993. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  92994. return false;
  92995. }
  92996. var mesh = abstractMesh;
  92997. if (!mesh.isVisible || !mesh.isEnabled()) {
  92998. return false;
  92999. }
  93000. if (mesh.instances.length > 0) {
  93001. return false;
  93002. }
  93003. if (mesh.skeleton || mesh.hasLODLevels) {
  93004. return false;
  93005. }
  93006. if (mesh.parent) {
  93007. return false;
  93008. }
  93009. return true;
  93010. };
  93011. return _this;
  93012. }
  93013. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  93014. /**
  93015. * Gets or sets a boolean which defines if optimization octree has to be updated
  93016. */
  93017. get: function () {
  93018. return MergeMeshesOptimization._UpdateSelectionTree;
  93019. },
  93020. /**
  93021. * Gets or sets a boolean which defines if optimization octree has to be updated
  93022. */
  93023. set: function (value) {
  93024. MergeMeshesOptimization._UpdateSelectionTree = value;
  93025. },
  93026. enumerable: true,
  93027. configurable: true
  93028. });
  93029. /**
  93030. * Gets a string describing the action executed by the current optimization
  93031. * @return description string
  93032. */
  93033. MergeMeshesOptimization.prototype.getDescription = function () {
  93034. return "Merging similar meshes together";
  93035. };
  93036. /**
  93037. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93038. * @param scene defines the current scene where to apply this optimization
  93039. * @param optimizer defines the current optimizer
  93040. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  93041. * @returns true if everything that can be done was applied
  93042. */
  93043. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  93044. var globalPool = scene.meshes.slice(0);
  93045. var globalLength = globalPool.length;
  93046. for (var index = 0; index < globalLength; index++) {
  93047. var currentPool = new Array();
  93048. var current = globalPool[index];
  93049. // Checks
  93050. if (!this._canBeMerged(current)) {
  93051. continue;
  93052. }
  93053. currentPool.push(current);
  93054. // Find compatible meshes
  93055. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  93056. var otherMesh = globalPool[subIndex];
  93057. if (!this._canBeMerged(otherMesh)) {
  93058. continue;
  93059. }
  93060. if (otherMesh.material !== current.material) {
  93061. continue;
  93062. }
  93063. if (otherMesh.checkCollisions !== current.checkCollisions) {
  93064. continue;
  93065. }
  93066. currentPool.push(otherMesh);
  93067. globalLength--;
  93068. globalPool.splice(subIndex, 1);
  93069. subIndex--;
  93070. }
  93071. if (currentPool.length < 2) {
  93072. continue;
  93073. }
  93074. // Merge meshes
  93075. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  93076. }
  93077. if (updateSelectionTree != undefined) {
  93078. if (updateSelectionTree) {
  93079. scene.createOrUpdateSelectionOctree();
  93080. }
  93081. }
  93082. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  93083. scene.createOrUpdateSelectionOctree();
  93084. }
  93085. return true;
  93086. };
  93087. ;
  93088. MergeMeshesOptimization._UpdateSelectionTree = false;
  93089. return MergeMeshesOptimization;
  93090. }(SceneOptimization));
  93091. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  93092. /**
  93093. * Defines a list of options used by SceneOptimizer
  93094. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93095. */
  93096. var SceneOptimizerOptions = /** @class */ (function () {
  93097. /**
  93098. * Creates a new list of options used by SceneOptimizer
  93099. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  93100. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  93101. */
  93102. function SceneOptimizerOptions(
  93103. /**
  93104. * Defines the target frame rate to reach (60 by default)
  93105. */
  93106. targetFrameRate,
  93107. /**
  93108. * Defines the interval between two checkes (2000ms by default)
  93109. */
  93110. trackerDuration) {
  93111. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  93112. if (trackerDuration === void 0) { trackerDuration = 2000; }
  93113. this.targetFrameRate = targetFrameRate;
  93114. this.trackerDuration = trackerDuration;
  93115. /**
  93116. * Gets the list of optimizations to apply
  93117. */
  93118. this.optimizations = new Array();
  93119. }
  93120. /**
  93121. * Add a new optimization
  93122. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  93123. * @returns the current SceneOptimizerOptions
  93124. */
  93125. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  93126. this.optimizations.push(optimization);
  93127. return this;
  93128. };
  93129. /**
  93130. * Add a new custom optimization
  93131. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  93132. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  93133. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93134. * @returns the current SceneOptimizerOptions
  93135. */
  93136. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  93137. if (priority === void 0) { priority = 0; }
  93138. var optimization = new CustomOptimization(priority);
  93139. optimization.onApply = onApply;
  93140. optimization.onGetDescription = onGetDescription;
  93141. this.optimizations.push(optimization);
  93142. return this;
  93143. };
  93144. /**
  93145. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  93146. * @param targetFrameRate defines the target frame rate (60 by default)
  93147. * @returns a SceneOptimizerOptions object
  93148. */
  93149. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  93150. var result = new SceneOptimizerOptions(targetFrameRate);
  93151. var priority = 0;
  93152. result.addOptimization(new MergeMeshesOptimization(priority));
  93153. result.addOptimization(new ShadowsOptimization(priority));
  93154. result.addOptimization(new LensFlaresOptimization(priority));
  93155. // Next priority
  93156. priority++;
  93157. result.addOptimization(new PostProcessesOptimization(priority));
  93158. result.addOptimization(new ParticlesOptimization(priority));
  93159. // Next priority
  93160. priority++;
  93161. result.addOptimization(new TextureOptimization(priority, 1024));
  93162. return result;
  93163. };
  93164. /**
  93165. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  93166. * @param targetFrameRate defines the target frame rate (60 by default)
  93167. * @returns a SceneOptimizerOptions object
  93168. */
  93169. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  93170. var result = new SceneOptimizerOptions(targetFrameRate);
  93171. var priority = 0;
  93172. result.addOptimization(new MergeMeshesOptimization(priority));
  93173. result.addOptimization(new ShadowsOptimization(priority));
  93174. result.addOptimization(new LensFlaresOptimization(priority));
  93175. // Next priority
  93176. priority++;
  93177. result.addOptimization(new PostProcessesOptimization(priority));
  93178. result.addOptimization(new ParticlesOptimization(priority));
  93179. // Next priority
  93180. priority++;
  93181. result.addOptimization(new TextureOptimization(priority, 512));
  93182. // Next priority
  93183. priority++;
  93184. result.addOptimization(new RenderTargetsOptimization(priority));
  93185. // Next priority
  93186. priority++;
  93187. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  93188. return result;
  93189. };
  93190. /**
  93191. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  93192. * @param targetFrameRate defines the target frame rate (60 by default)
  93193. * @returns a SceneOptimizerOptions object
  93194. */
  93195. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  93196. var result = new SceneOptimizerOptions(targetFrameRate);
  93197. var priority = 0;
  93198. result.addOptimization(new MergeMeshesOptimization(priority));
  93199. result.addOptimization(new ShadowsOptimization(priority));
  93200. result.addOptimization(new LensFlaresOptimization(priority));
  93201. // Next priority
  93202. priority++;
  93203. result.addOptimization(new PostProcessesOptimization(priority));
  93204. result.addOptimization(new ParticlesOptimization(priority));
  93205. // Next priority
  93206. priority++;
  93207. result.addOptimization(new TextureOptimization(priority, 256));
  93208. // Next priority
  93209. priority++;
  93210. result.addOptimization(new RenderTargetsOptimization(priority));
  93211. // Next priority
  93212. priority++;
  93213. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  93214. return result;
  93215. };
  93216. return SceneOptimizerOptions;
  93217. }());
  93218. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  93219. /**
  93220. * Class used to run optimizations in order to reach a target frame rate
  93221. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93222. */
  93223. var SceneOptimizer = /** @class */ (function () {
  93224. /**
  93225. * Creates a new SceneOptimizer
  93226. * @param scene defines the scene to work on
  93227. * @param options defines the options to use with the SceneOptimizer
  93228. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  93229. * @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)
  93230. */
  93231. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  93232. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  93233. if (improvementMode === void 0) { improvementMode = false; }
  93234. var _this = this;
  93235. this._isRunning = false;
  93236. this._currentPriorityLevel = 0;
  93237. this._targetFrameRate = 60;
  93238. this._trackerDuration = 2000;
  93239. this._currentFrameRate = 0;
  93240. this._improvementMode = false;
  93241. /**
  93242. * Defines an observable called when the optimizer reaches the target frame rate
  93243. */
  93244. this.onSuccessObservable = new BABYLON.Observable();
  93245. /**
  93246. * Defines an observable called when the optimizer enables an optimization
  93247. */
  93248. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  93249. /**
  93250. * Defines an observable called when the optimizer is not able to reach the target frame rate
  93251. */
  93252. this.onFailureObservable = new BABYLON.Observable();
  93253. if (!options) {
  93254. this._options = new SceneOptimizerOptions();
  93255. }
  93256. else {
  93257. this._options = options;
  93258. }
  93259. if (this._options.targetFrameRate) {
  93260. this._targetFrameRate = this._options.targetFrameRate;
  93261. }
  93262. if (this._options.trackerDuration) {
  93263. this._trackerDuration = this._options.trackerDuration;
  93264. }
  93265. if (autoGeneratePriorities) {
  93266. var priority = 0;
  93267. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  93268. var optim = _a[_i];
  93269. optim.priority = priority++;
  93270. }
  93271. }
  93272. this._improvementMode = improvementMode;
  93273. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93274. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  93275. _this._sceneDisposeObserver = null;
  93276. _this.dispose();
  93277. });
  93278. }
  93279. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  93280. /**
  93281. * Gets a boolean indicating if the optimizer is in improvement mode
  93282. */
  93283. get: function () {
  93284. return this._improvementMode;
  93285. },
  93286. enumerable: true,
  93287. configurable: true
  93288. });
  93289. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  93290. /**
  93291. * Gets the current priority level (0 at start)
  93292. */
  93293. get: function () {
  93294. return this._currentPriorityLevel;
  93295. },
  93296. enumerable: true,
  93297. configurable: true
  93298. });
  93299. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  93300. /**
  93301. * Gets the current frame rate checked by the SceneOptimizer
  93302. */
  93303. get: function () {
  93304. return this._currentFrameRate;
  93305. },
  93306. enumerable: true,
  93307. configurable: true
  93308. });
  93309. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  93310. /**
  93311. * Gets or sets the current target frame rate (60 by default)
  93312. */
  93313. get: function () {
  93314. return this._targetFrameRate;
  93315. },
  93316. /**
  93317. * Gets or sets the current target frame rate (60 by default)
  93318. */
  93319. set: function (value) {
  93320. this._targetFrameRate = value;
  93321. },
  93322. enumerable: true,
  93323. configurable: true
  93324. });
  93325. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  93326. /**
  93327. * Gets or sets the current interval between two checks (every 2000ms by default)
  93328. */
  93329. get: function () {
  93330. return this._trackerDuration;
  93331. },
  93332. /**
  93333. * Gets or sets the current interval between two checks (every 2000ms by default)
  93334. */
  93335. set: function (value) {
  93336. this._trackerDuration = value;
  93337. },
  93338. enumerable: true,
  93339. configurable: true
  93340. });
  93341. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  93342. /**
  93343. * Gets the list of active optimizations
  93344. */
  93345. get: function () {
  93346. return this._options.optimizations;
  93347. },
  93348. enumerable: true,
  93349. configurable: true
  93350. });
  93351. /**
  93352. * Stops the current optimizer
  93353. */
  93354. SceneOptimizer.prototype.stop = function () {
  93355. this._isRunning = false;
  93356. };
  93357. /**
  93358. * Reset the optimizer to initial step (current priority level = 0)
  93359. */
  93360. SceneOptimizer.prototype.reset = function () {
  93361. this._currentPriorityLevel = 0;
  93362. };
  93363. /**
  93364. * Start the optimizer. By default it will try to reach a specific framerate
  93365. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  93366. */
  93367. SceneOptimizer.prototype.start = function () {
  93368. var _this = this;
  93369. if (this._isRunning) {
  93370. return;
  93371. }
  93372. this._isRunning = true;
  93373. // Let's wait for the scene to be ready before running our check
  93374. this._scene.executeWhenReady(function () {
  93375. setTimeout(function () {
  93376. _this._checkCurrentState();
  93377. }, _this._trackerDuration);
  93378. });
  93379. };
  93380. SceneOptimizer.prototype._checkCurrentState = function () {
  93381. var _this = this;
  93382. if (!this._isRunning) {
  93383. return;
  93384. }
  93385. var scene = this._scene;
  93386. var options = this._options;
  93387. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  93388. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  93389. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  93390. this._isRunning = false;
  93391. this.onSuccessObservable.notifyObservers(this);
  93392. return;
  93393. }
  93394. // Apply current level of optimizations
  93395. var allDone = true;
  93396. var noOptimizationApplied = true;
  93397. for (var index = 0; index < options.optimizations.length; index++) {
  93398. var optimization = options.optimizations[index];
  93399. if (optimization.priority === this._currentPriorityLevel) {
  93400. noOptimizationApplied = false;
  93401. allDone = allDone && optimization.apply(scene, this);
  93402. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  93403. }
  93404. }
  93405. // If no optimization was applied, this is a failure :(
  93406. if (noOptimizationApplied) {
  93407. this._isRunning = false;
  93408. this.onFailureObservable.notifyObservers(this);
  93409. return;
  93410. }
  93411. // If all optimizations were done, move to next level
  93412. if (allDone) {
  93413. this._currentPriorityLevel++;
  93414. }
  93415. // Let's the system running for a specific amount of time before checking FPS
  93416. scene.executeWhenReady(function () {
  93417. setTimeout(function () {
  93418. _this._checkCurrentState();
  93419. }, _this._trackerDuration);
  93420. });
  93421. };
  93422. /**
  93423. * Release all resources
  93424. */
  93425. SceneOptimizer.prototype.dispose = function () {
  93426. this.stop();
  93427. this.onSuccessObservable.clear();
  93428. this.onFailureObservable.clear();
  93429. this.onNewOptimizationAppliedObservable.clear();
  93430. if (this._sceneDisposeObserver) {
  93431. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93432. }
  93433. };
  93434. /**
  93435. * Helper function to create a SceneOptimizer with one single line of code
  93436. * @param scene defines the scene to work on
  93437. * @param options defines the options to use with the SceneOptimizer
  93438. * @param onSuccess defines a callback to call on success
  93439. * @param onFailure defines a callback to call on failure
  93440. * @returns the new SceneOptimizer object
  93441. */
  93442. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  93443. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  93444. if (onSuccess) {
  93445. optimizer.onSuccessObservable.add(function () {
  93446. onSuccess();
  93447. });
  93448. }
  93449. if (onFailure) {
  93450. optimizer.onFailureObservable.add(function () {
  93451. onFailure();
  93452. });
  93453. }
  93454. optimizer.start();
  93455. return optimizer;
  93456. };
  93457. return SceneOptimizer;
  93458. }());
  93459. BABYLON.SceneOptimizer = SceneOptimizer;
  93460. })(BABYLON || (BABYLON = {}));
  93461. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  93462. var BABYLON;
  93463. (function (BABYLON) {
  93464. var OutlineRenderer = /** @class */ (function () {
  93465. function OutlineRenderer(scene) {
  93466. this.zOffset = 1;
  93467. this._scene = scene;
  93468. }
  93469. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  93470. var _this = this;
  93471. if (useOverlay === void 0) { useOverlay = false; }
  93472. var scene = this._scene;
  93473. var engine = this._scene.getEngine();
  93474. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93475. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  93476. return;
  93477. }
  93478. var mesh = subMesh.getRenderingMesh();
  93479. var material = subMesh.getMaterial();
  93480. if (!material || !scene.activeCamera) {
  93481. return;
  93482. }
  93483. engine.enableEffect(this._effect);
  93484. // Logarithmic depth
  93485. if (material.useLogarithmicDepth) {
  93486. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  93487. }
  93488. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  93489. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  93490. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  93491. // Bones
  93492. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93493. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93494. }
  93495. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  93496. // Alpha test
  93497. if (material && material.needAlphaTesting()) {
  93498. var alphaTexture = material.getAlphaTestTexture();
  93499. if (alphaTexture) {
  93500. this._effect.setTexture("diffuseSampler", alphaTexture);
  93501. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  93502. }
  93503. }
  93504. engine.setZOffset(-this.zOffset);
  93505. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  93506. engine.setZOffset(0);
  93507. };
  93508. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  93509. var defines = [];
  93510. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  93511. var mesh = subMesh.getMesh();
  93512. var material = subMesh.getMaterial();
  93513. if (material) {
  93514. // Alpha test
  93515. if (material.needAlphaTesting()) {
  93516. defines.push("#define ALPHATEST");
  93517. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93518. attribs.push(BABYLON.VertexBuffer.UVKind);
  93519. defines.push("#define UV1");
  93520. }
  93521. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  93522. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93523. defines.push("#define UV2");
  93524. }
  93525. }
  93526. //Logarithmic depth
  93527. if (material.useLogarithmicDepth) {
  93528. defines.push("#define LOGARITHMICDEPTH");
  93529. }
  93530. }
  93531. // Bones
  93532. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93533. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93534. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93535. if (mesh.numBoneInfluencers > 4) {
  93536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93538. }
  93539. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93540. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  93541. }
  93542. else {
  93543. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93544. }
  93545. // Instances
  93546. if (useInstances) {
  93547. defines.push("#define INSTANCES");
  93548. attribs.push("world0");
  93549. attribs.push("world1");
  93550. attribs.push("world2");
  93551. attribs.push("world3");
  93552. }
  93553. // Get correct effect
  93554. var join = defines.join("\n");
  93555. if (this._cachedDefines !== join) {
  93556. this._cachedDefines = join;
  93557. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  93558. }
  93559. return this._effect.isReady();
  93560. };
  93561. return OutlineRenderer;
  93562. }());
  93563. BABYLON.OutlineRenderer = OutlineRenderer;
  93564. })(BABYLON || (BABYLON = {}));
  93565. //# sourceMappingURL=babylon.outlineRenderer.js.map
  93566. var BABYLON;
  93567. (function (BABYLON) {
  93568. var FaceAdjacencies = /** @class */ (function () {
  93569. function FaceAdjacencies() {
  93570. this.edges = new Array();
  93571. this.edgesConnectedCount = 0;
  93572. }
  93573. return FaceAdjacencies;
  93574. }());
  93575. var EdgesRenderer = /** @class */ (function () {
  93576. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  93577. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  93578. if (epsilon === void 0) { epsilon = 0.95; }
  93579. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  93580. this.edgesWidthScalerForOrthographic = 1000.0;
  93581. this.edgesWidthScalerForPerspective = 50.0;
  93582. this._linesPositions = new Array();
  93583. this._linesNormals = new Array();
  93584. this._linesIndices = new Array();
  93585. this._buffers = {};
  93586. this._checkVerticesInsteadOfIndices = false;
  93587. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  93588. this.isEnabled = true;
  93589. this._source = source;
  93590. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  93591. this._epsilon = epsilon;
  93592. this._prepareRessources();
  93593. this._generateEdgesLines();
  93594. }
  93595. EdgesRenderer.prototype._prepareRessources = function () {
  93596. if (this._lineShader) {
  93597. return;
  93598. }
  93599. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  93600. attributes: ["position", "normal"],
  93601. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  93602. });
  93603. this._lineShader.disableDepthWrite = true;
  93604. this._lineShader.backFaceCulling = false;
  93605. };
  93606. EdgesRenderer.prototype._rebuild = function () {
  93607. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93608. if (buffer) {
  93609. buffer._rebuild();
  93610. }
  93611. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93612. if (buffer) {
  93613. buffer._rebuild();
  93614. }
  93615. var scene = this._source.getScene();
  93616. var engine = scene.getEngine();
  93617. this._ib = engine.createIndexBuffer(this._linesIndices);
  93618. };
  93619. EdgesRenderer.prototype.dispose = function () {
  93620. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93621. if (buffer) {
  93622. buffer.dispose();
  93623. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  93624. }
  93625. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93626. if (buffer) {
  93627. buffer.dispose();
  93628. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  93629. }
  93630. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  93631. this._lineShader.dispose();
  93632. };
  93633. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  93634. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  93635. return 0;
  93636. }
  93637. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  93638. return 1;
  93639. }
  93640. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  93641. return 2;
  93642. }
  93643. return -1;
  93644. };
  93645. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  93646. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  93647. return 0;
  93648. }
  93649. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  93650. return 1;
  93651. }
  93652. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  93653. return 2;
  93654. }
  93655. return -1;
  93656. };
  93657. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  93658. var needToCreateLine;
  93659. if (edge === undefined) {
  93660. needToCreateLine = true;
  93661. }
  93662. else {
  93663. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  93664. needToCreateLine = dotProduct < this._epsilon;
  93665. }
  93666. if (needToCreateLine) {
  93667. var offset = this._linesPositions.length / 3;
  93668. var normal = p0.subtract(p1);
  93669. normal.normalize();
  93670. // Positions
  93671. this._linesPositions.push(p0.x);
  93672. this._linesPositions.push(p0.y);
  93673. this._linesPositions.push(p0.z);
  93674. this._linesPositions.push(p0.x);
  93675. this._linesPositions.push(p0.y);
  93676. this._linesPositions.push(p0.z);
  93677. this._linesPositions.push(p1.x);
  93678. this._linesPositions.push(p1.y);
  93679. this._linesPositions.push(p1.z);
  93680. this._linesPositions.push(p1.x);
  93681. this._linesPositions.push(p1.y);
  93682. this._linesPositions.push(p1.z);
  93683. // Normals
  93684. this._linesNormals.push(p1.x);
  93685. this._linesNormals.push(p1.y);
  93686. this._linesNormals.push(p1.z);
  93687. this._linesNormals.push(-1);
  93688. this._linesNormals.push(p1.x);
  93689. this._linesNormals.push(p1.y);
  93690. this._linesNormals.push(p1.z);
  93691. this._linesNormals.push(1);
  93692. this._linesNormals.push(p0.x);
  93693. this._linesNormals.push(p0.y);
  93694. this._linesNormals.push(p0.z);
  93695. this._linesNormals.push(-1);
  93696. this._linesNormals.push(p0.x);
  93697. this._linesNormals.push(p0.y);
  93698. this._linesNormals.push(p0.z);
  93699. this._linesNormals.push(1);
  93700. // Indices
  93701. this._linesIndices.push(offset);
  93702. this._linesIndices.push(offset + 1);
  93703. this._linesIndices.push(offset + 2);
  93704. this._linesIndices.push(offset);
  93705. this._linesIndices.push(offset + 2);
  93706. this._linesIndices.push(offset + 3);
  93707. }
  93708. };
  93709. EdgesRenderer.prototype._generateEdgesLines = function () {
  93710. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93711. var indices = this._source.getIndices();
  93712. if (!indices || !positions) {
  93713. return;
  93714. }
  93715. // First let's find adjacencies
  93716. var adjacencies = new Array();
  93717. var faceNormals = new Array();
  93718. var index;
  93719. var faceAdjacencies;
  93720. // Prepare faces
  93721. for (index = 0; index < indices.length; index += 3) {
  93722. faceAdjacencies = new FaceAdjacencies();
  93723. var p0Index = indices[index];
  93724. var p1Index = indices[index + 1];
  93725. var p2Index = indices[index + 2];
  93726. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  93727. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  93728. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  93729. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  93730. faceNormal.normalize();
  93731. faceNormals.push(faceNormal);
  93732. adjacencies.push(faceAdjacencies);
  93733. }
  93734. // Scan
  93735. for (index = 0; index < adjacencies.length; index++) {
  93736. faceAdjacencies = adjacencies[index];
  93737. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  93738. var otherFaceAdjacencies = adjacencies[otherIndex];
  93739. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  93740. break;
  93741. }
  93742. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  93743. continue;
  93744. }
  93745. var otherP0 = indices[otherIndex * 3];
  93746. var otherP1 = indices[otherIndex * 3 + 1];
  93747. var otherP2 = indices[otherIndex * 3 + 2];
  93748. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  93749. var otherEdgeIndex = 0;
  93750. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  93751. continue;
  93752. }
  93753. switch (edgeIndex) {
  93754. case 0:
  93755. if (this._checkVerticesInsteadOfIndices) {
  93756. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93757. }
  93758. else {
  93759. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  93760. }
  93761. break;
  93762. case 1:
  93763. if (this._checkVerticesInsteadOfIndices) {
  93764. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93765. }
  93766. else {
  93767. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  93768. }
  93769. break;
  93770. case 2:
  93771. if (this._checkVerticesInsteadOfIndices) {
  93772. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93773. }
  93774. else {
  93775. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  93776. }
  93777. break;
  93778. }
  93779. if (otherEdgeIndex === -1) {
  93780. continue;
  93781. }
  93782. faceAdjacencies.edges[edgeIndex] = otherIndex;
  93783. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  93784. faceAdjacencies.edgesConnectedCount++;
  93785. otherFaceAdjacencies.edgesConnectedCount++;
  93786. if (faceAdjacencies.edgesConnectedCount === 3) {
  93787. break;
  93788. }
  93789. }
  93790. }
  93791. }
  93792. // Create lines
  93793. for (index = 0; index < adjacencies.length; index++) {
  93794. // 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
  93795. var current = adjacencies[index];
  93796. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  93797. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  93798. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  93799. }
  93800. // Merge into a single mesh
  93801. var engine = this._source.getScene().getEngine();
  93802. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  93803. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  93804. this._ib = engine.createIndexBuffer(this._linesIndices);
  93805. this._indicesCount = this._linesIndices.length;
  93806. };
  93807. EdgesRenderer.prototype.render = function () {
  93808. var scene = this._source.getScene();
  93809. if (!this._lineShader.isReady() || !scene.activeCamera) {
  93810. return;
  93811. }
  93812. var engine = scene.getEngine();
  93813. this._lineShader._preBind();
  93814. // VBOs
  93815. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  93816. scene.resetCachedMaterial();
  93817. this._lineShader.setColor4("color", this._source.edgesColor);
  93818. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  93819. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  93820. }
  93821. else {
  93822. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  93823. }
  93824. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  93825. this._lineShader.bind(this._source.getWorldMatrix());
  93826. // Draw order
  93827. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  93828. this._lineShader.unbind();
  93829. engine.setDepthWrite(true);
  93830. };
  93831. return EdgesRenderer;
  93832. }());
  93833. BABYLON.EdgesRenderer = EdgesRenderer;
  93834. })(BABYLON || (BABYLON = {}));
  93835. //# sourceMappingURL=babylon.edgesRenderer.js.map
  93836. var __assign = (this && this.__assign) || Object.assign || function(t) {
  93837. for (var s, i = 1, n = arguments.length; i < n; i++) {
  93838. s = arguments[i];
  93839. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  93840. t[p] = s[p];
  93841. }
  93842. return t;
  93843. };
  93844. var BABYLON;
  93845. (function (BABYLON) {
  93846. /**
  93847. * The effect layer Helps adding post process effect blended with the main pass.
  93848. *
  93849. * This can be for instance use to generate glow or higlight effects on the scene.
  93850. *
  93851. * The effect layer class can not be used directly and is intented to inherited from to be
  93852. * customized per effects.
  93853. */
  93854. var EffectLayer = /** @class */ (function () {
  93855. /**
  93856. * Instantiates a new effect Layer and references it in the scene.
  93857. * @param name The name of the layer
  93858. * @param scene The scene to use the layer in
  93859. */
  93860. function EffectLayer(
  93861. /** The Friendly of the effect in the scene */
  93862. name, scene) {
  93863. this._vertexBuffers = {};
  93864. this._maxSize = 0;
  93865. this._mainTextureDesiredSize = { width: 0, height: 0 };
  93866. this._shouldRender = true;
  93867. this._postProcesses = [];
  93868. this._textures = [];
  93869. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  93870. /**
  93871. * The clear color of the texture used to generate the glow map.
  93872. */
  93873. this.neutralColor = new BABYLON.Color4();
  93874. /**
  93875. * Specifies wether the highlight layer is enabled or not.
  93876. */
  93877. this.isEnabled = true;
  93878. /**
  93879. * An event triggered when the effect layer has been disposed.
  93880. */
  93881. this.onDisposeObservable = new BABYLON.Observable();
  93882. /**
  93883. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  93884. */
  93885. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  93886. /**
  93887. * An event triggered when the generated texture is being merged in the scene.
  93888. */
  93889. this.onBeforeComposeObservable = new BABYLON.Observable();
  93890. /**
  93891. * An event triggered when the generated texture has been merged in the scene.
  93892. */
  93893. this.onAfterComposeObservable = new BABYLON.Observable();
  93894. /**
  93895. * An event triggered when the efffect layer changes its size.
  93896. */
  93897. this.onSizeChangedObservable = new BABYLON.Observable();
  93898. this.name = name;
  93899. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93900. this._engine = scene.getEngine();
  93901. this._maxSize = this._engine.getCaps().maxTextureSize;
  93902. this._scene.effectLayers.push(this);
  93903. // Generate Buffers
  93904. this._generateIndexBuffer();
  93905. this._genrateVertexBuffer();
  93906. }
  93907. Object.defineProperty(EffectLayer.prototype, "camera", {
  93908. /**
  93909. * Gets the camera attached to the layer.
  93910. */
  93911. get: function () {
  93912. return this._effectLayerOptions.camera;
  93913. },
  93914. enumerable: true,
  93915. configurable: true
  93916. });
  93917. /**
  93918. * Initializes the effect layer with the required options.
  93919. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  93920. */
  93921. EffectLayer.prototype._init = function (options) {
  93922. // Adapt options
  93923. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  93924. this._setMainTextureSize();
  93925. this._createMainTexture();
  93926. this._createTextureAndPostProcesses();
  93927. this._mergeEffect = this._createMergeEffect();
  93928. };
  93929. /**
  93930. * Generates the index buffer of the full screen quad blending to the main canvas.
  93931. */
  93932. EffectLayer.prototype._generateIndexBuffer = function () {
  93933. // Indices
  93934. var indices = [];
  93935. indices.push(0);
  93936. indices.push(1);
  93937. indices.push(2);
  93938. indices.push(0);
  93939. indices.push(2);
  93940. indices.push(3);
  93941. this._indexBuffer = this._engine.createIndexBuffer(indices);
  93942. };
  93943. /**
  93944. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  93945. */
  93946. EffectLayer.prototype._genrateVertexBuffer = function () {
  93947. // VBO
  93948. var vertices = [];
  93949. vertices.push(1, 1);
  93950. vertices.push(-1, 1);
  93951. vertices.push(-1, -1);
  93952. vertices.push(1, -1);
  93953. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93954. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93955. };
  93956. /**
  93957. * Sets the main texture desired size which is the closest power of two
  93958. * of the engine canvas size.
  93959. */
  93960. EffectLayer.prototype._setMainTextureSize = function () {
  93961. if (this._effectLayerOptions.mainTextureFixedSize) {
  93962. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  93963. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  93964. }
  93965. else {
  93966. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  93967. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  93968. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  93969. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  93970. }
  93971. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  93972. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  93973. };
  93974. /**
  93975. * Creates the main texture for the effect layer.
  93976. */
  93977. EffectLayer.prototype._createMainTexture = function () {
  93978. var _this = this;
  93979. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  93980. width: this._mainTextureDesiredSize.width,
  93981. height: this._mainTextureDesiredSize.height
  93982. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93983. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  93984. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93985. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93986. this._mainTexture.anisotropicFilteringLevel = 1;
  93987. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93988. this._mainTexture.renderParticles = false;
  93989. this._mainTexture.renderList = null;
  93990. this._mainTexture.ignoreCameraViewport = true;
  93991. // Custom render function
  93992. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  93993. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  93994. var index;
  93995. var engine = _this._scene.getEngine();
  93996. if (depthOnlySubMeshes.length) {
  93997. engine.setColorWrite(false);
  93998. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  93999. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  94000. }
  94001. engine.setColorWrite(true);
  94002. }
  94003. for (index = 0; index < opaqueSubMeshes.length; index++) {
  94004. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  94005. }
  94006. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  94007. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  94008. }
  94009. for (index = 0; index < transparentSubMeshes.length; index++) {
  94010. _this._renderSubMesh(transparentSubMeshes.data[index]);
  94011. }
  94012. };
  94013. this._mainTexture.onClearObservable.add(function (engine) {
  94014. engine.clear(_this.neutralColor, true, true, true);
  94015. });
  94016. };
  94017. /**
  94018. * Checks for the readiness of the element composing the layer.
  94019. * @param subMesh the mesh to check for
  94020. * @param useInstances specify wether or not to use instances to render the mesh
  94021. * @param emissiveTexture the associated emissive texture used to generate the glow
  94022. * @return true if ready otherwise, false
  94023. */
  94024. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  94025. var material = subMesh.getMaterial();
  94026. if (!material) {
  94027. return false;
  94028. }
  94029. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  94030. return false;
  94031. }
  94032. var defines = [];
  94033. var attribs = [BABYLON.VertexBuffer.PositionKind];
  94034. var mesh = subMesh.getMesh();
  94035. var uv1 = false;
  94036. var uv2 = false;
  94037. // Alpha test
  94038. if (material && material.needAlphaTesting()) {
  94039. var alphaTexture = material.getAlphaTestTexture();
  94040. if (alphaTexture) {
  94041. defines.push("#define ALPHATEST");
  94042. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94043. alphaTexture.coordinatesIndex === 1) {
  94044. defines.push("#define DIFFUSEUV2");
  94045. uv2 = true;
  94046. }
  94047. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94048. defines.push("#define DIFFUSEUV1");
  94049. uv1 = true;
  94050. }
  94051. }
  94052. }
  94053. // Emissive
  94054. if (emissiveTexture) {
  94055. defines.push("#define EMISSIVE");
  94056. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94057. emissiveTexture.coordinatesIndex === 1) {
  94058. defines.push("#define EMISSIVEUV2");
  94059. uv2 = true;
  94060. }
  94061. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94062. defines.push("#define EMISSIVEUV1");
  94063. uv1 = true;
  94064. }
  94065. }
  94066. if (uv1) {
  94067. attribs.push(BABYLON.VertexBuffer.UVKind);
  94068. defines.push("#define UV1");
  94069. }
  94070. if (uv2) {
  94071. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94072. defines.push("#define UV2");
  94073. }
  94074. // Bones
  94075. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94076. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94077. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94078. if (mesh.numBoneInfluencers > 4) {
  94079. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94080. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94081. }
  94082. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94083. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  94084. }
  94085. else {
  94086. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94087. }
  94088. // Morph targets
  94089. var manager = mesh.morphTargetManager;
  94090. var morphInfluencers = 0;
  94091. if (manager) {
  94092. if (manager.numInfluencers > 0) {
  94093. defines.push("#define MORPHTARGETS");
  94094. morphInfluencers = manager.numInfluencers;
  94095. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  94096. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  94097. }
  94098. }
  94099. // Instances
  94100. if (useInstances) {
  94101. defines.push("#define INSTANCES");
  94102. attribs.push("world0");
  94103. attribs.push("world1");
  94104. attribs.push("world2");
  94105. attribs.push("world3");
  94106. }
  94107. // Get correct effect
  94108. var join = defines.join("\n");
  94109. if (this._cachedDefines !== join) {
  94110. this._cachedDefines = join;
  94111. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  94112. }
  94113. return this._effectLayerMapGenerationEffect.isReady();
  94114. };
  94115. /**
  94116. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  94117. */
  94118. EffectLayer.prototype.render = function () {
  94119. var currentEffect = this._mergeEffect;
  94120. // Check
  94121. if (!currentEffect.isReady())
  94122. return;
  94123. for (var i = 0; i < this._postProcesses.length; i++) {
  94124. if (!this._postProcesses[i].isReady()) {
  94125. return;
  94126. }
  94127. }
  94128. var engine = this._scene.getEngine();
  94129. this.onBeforeComposeObservable.notifyObservers(this);
  94130. // Render
  94131. engine.enableEffect(currentEffect);
  94132. engine.setState(false);
  94133. // VBOs
  94134. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94135. // Cache
  94136. var previousAlphaMode = engine.getAlphaMode();
  94137. // Go Blend.
  94138. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  94139. // Blends the map on the main canvas.
  94140. this._internalRender(currentEffect);
  94141. // Restore Alpha
  94142. engine.setAlphaMode(previousAlphaMode);
  94143. this.onAfterComposeObservable.notifyObservers(this);
  94144. // Handle size changes.
  94145. var size = this._mainTexture.getSize();
  94146. this._setMainTextureSize();
  94147. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  94148. // Recreate RTT and post processes on size change.
  94149. this.onSizeChangedObservable.notifyObservers(this);
  94150. this._disposeTextureAndPostProcesses();
  94151. this._createMainTexture();
  94152. this._createTextureAndPostProcesses();
  94153. }
  94154. };
  94155. /**
  94156. * Determine if a given mesh will be used in the current effect.
  94157. * @param mesh mesh to test
  94158. * @returns true if the mesh will be used
  94159. */
  94160. EffectLayer.prototype.hasMesh = function (mesh) {
  94161. return true;
  94162. };
  94163. /**
  94164. * Returns true if the layer contains information to display, otherwise false.
  94165. * @returns true if the glow layer should be rendered
  94166. */
  94167. EffectLayer.prototype.shouldRender = function () {
  94168. return this.isEnabled && this._shouldRender;
  94169. };
  94170. /**
  94171. * Returns true if the mesh should render, otherwise false.
  94172. * @param mesh The mesh to render
  94173. * @returns true if it should render otherwise false
  94174. */
  94175. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  94176. return true;
  94177. };
  94178. /**
  94179. * Returns true if the mesh should render, otherwise false.
  94180. * @param mesh The mesh to render
  94181. * @returns true if it should render otherwise false
  94182. */
  94183. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  94184. return true;
  94185. };
  94186. /**
  94187. * Renders the submesh passed in parameter to the generation map.
  94188. */
  94189. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  94190. var _this = this;
  94191. if (!this.shouldRender()) {
  94192. return;
  94193. }
  94194. var material = subMesh.getMaterial();
  94195. var mesh = subMesh.getRenderingMesh();
  94196. var scene = this._scene;
  94197. var engine = scene.getEngine();
  94198. if (!material) {
  94199. return;
  94200. }
  94201. // Do not block in blend mode.
  94202. if (material.needAlphaBlendingForMesh(mesh)) {
  94203. return;
  94204. }
  94205. // Culling
  94206. engine.setState(material.backFaceCulling);
  94207. // Managing instances
  94208. var batch = mesh._getInstancesRenderList(subMesh._id);
  94209. if (batch.mustReturn) {
  94210. return;
  94211. }
  94212. // Early Exit per mesh
  94213. if (!this._shouldRenderMesh(mesh)) {
  94214. return;
  94215. }
  94216. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94217. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  94218. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  94219. engine.enableEffect(this._effectLayerMapGenerationEffect);
  94220. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  94221. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  94222. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  94223. // Alpha test
  94224. if (material && material.needAlphaTesting()) {
  94225. var alphaTexture = material.getAlphaTestTexture();
  94226. if (alphaTexture) {
  94227. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  94228. var textureMatrix = alphaTexture.getTextureMatrix();
  94229. if (textureMatrix) {
  94230. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  94231. }
  94232. }
  94233. }
  94234. // Glow emissive only
  94235. if (this._emissiveTextureAndColor.texture) {
  94236. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  94237. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  94238. }
  94239. // Bones
  94240. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94241. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94242. }
  94243. // Morph targets
  94244. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  94245. // Draw
  94246. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  94247. }
  94248. else {
  94249. // Need to reset refresh rate of the shadowMap
  94250. this._mainTexture.resetRefreshCounter();
  94251. }
  94252. };
  94253. /**
  94254. * Rebuild the required buffers.
  94255. * @hidden Internal use only.
  94256. */
  94257. EffectLayer.prototype._rebuild = function () {
  94258. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94259. if (vb) {
  94260. vb._rebuild();
  94261. }
  94262. this._generateIndexBuffer();
  94263. };
  94264. /**
  94265. * Dispose only the render target textures and post process.
  94266. */
  94267. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  94268. this._mainTexture.dispose();
  94269. for (var i = 0; i < this._postProcesses.length; i++) {
  94270. if (this._postProcesses[i]) {
  94271. this._postProcesses[i].dispose();
  94272. }
  94273. }
  94274. this._postProcesses = [];
  94275. for (var i = 0; i < this._textures.length; i++) {
  94276. if (this._textures[i]) {
  94277. this._textures[i].dispose();
  94278. }
  94279. }
  94280. this._textures = [];
  94281. };
  94282. /**
  94283. * Dispose the highlight layer and free resources.
  94284. */
  94285. EffectLayer.prototype.dispose = function () {
  94286. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94287. if (vertexBuffer) {
  94288. vertexBuffer.dispose();
  94289. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94290. }
  94291. if (this._indexBuffer) {
  94292. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94293. this._indexBuffer = null;
  94294. }
  94295. // Clean textures and post processes
  94296. this._disposeTextureAndPostProcesses();
  94297. // Remove from scene
  94298. var index = this._scene.effectLayers.indexOf(this, 0);
  94299. if (index > -1) {
  94300. this._scene.effectLayers.splice(index, 1);
  94301. }
  94302. // Callback
  94303. this.onDisposeObservable.notifyObservers(this);
  94304. this.onDisposeObservable.clear();
  94305. this.onBeforeRenderMainTextureObservable.clear();
  94306. this.onBeforeComposeObservable.clear();
  94307. this.onAfterComposeObservable.clear();
  94308. this.onSizeChangedObservable.clear();
  94309. };
  94310. /**
  94311. * Gets the class name of the effect layer
  94312. * @returns the string with the class name of the effect layer
  94313. */
  94314. EffectLayer.prototype.getClassName = function () {
  94315. return "EffectLayer";
  94316. };
  94317. /**
  94318. * Creates an effect layer from parsed effect layer data
  94319. * @param parsedEffectLayer defines effect layer data
  94320. * @param scene defines the current scene
  94321. * @param rootUrl defines the root URL containing the effect layer information
  94322. * @returns a parsed effect Layer
  94323. */
  94324. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  94325. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  94326. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  94327. };
  94328. __decorate([
  94329. BABYLON.serialize()
  94330. ], EffectLayer.prototype, "name", void 0);
  94331. __decorate([
  94332. BABYLON.serializeAsColor4()
  94333. ], EffectLayer.prototype, "neutralColor", void 0);
  94334. __decorate([
  94335. BABYLON.serialize()
  94336. ], EffectLayer.prototype, "isEnabled", void 0);
  94337. __decorate([
  94338. BABYLON.serializeAsCameraReference()
  94339. ], EffectLayer.prototype, "camera", null);
  94340. return EffectLayer;
  94341. }());
  94342. BABYLON.EffectLayer = EffectLayer;
  94343. })(BABYLON || (BABYLON = {}));
  94344. //# sourceMappingURL=babylon.effectLayer.js.map
  94345. var BABYLON;
  94346. (function (BABYLON) {
  94347. /**
  94348. * Special Glow Blur post process only blurring the alpha channel
  94349. * It enforces keeping the most luminous color in the color channel.
  94350. */
  94351. var GlowBlurPostProcess = /** @class */ (function (_super) {
  94352. __extends(GlowBlurPostProcess, _super);
  94353. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  94354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  94355. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  94356. _this.direction = direction;
  94357. _this.kernel = kernel;
  94358. _this.onApplyObservable.add(function (effect) {
  94359. effect.setFloat2("screenSize", _this.width, _this.height);
  94360. effect.setVector2("direction", _this.direction);
  94361. effect.setFloat("blurWidth", _this.kernel);
  94362. });
  94363. return _this;
  94364. }
  94365. return GlowBlurPostProcess;
  94366. }(BABYLON.PostProcess));
  94367. /**
  94368. * The highlight layer Helps adding a glow effect around a mesh.
  94369. *
  94370. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94371. * glowy meshes to your scene.
  94372. *
  94373. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  94374. */
  94375. var HighlightLayer = /** @class */ (function (_super) {
  94376. __extends(HighlightLayer, _super);
  94377. /**
  94378. * Instantiates a new highlight Layer and references it to the scene..
  94379. * @param name The name of the layer
  94380. * @param scene The scene to use the layer in
  94381. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  94382. */
  94383. function HighlightLayer(name, scene, options) {
  94384. var _this = _super.call(this, name, scene) || this;
  94385. _this.name = name;
  94386. /**
  94387. * Specifies whether or not the inner glow is ACTIVE in the layer.
  94388. */
  94389. _this.innerGlow = true;
  94390. /**
  94391. * Specifies whether or not the outer glow is ACTIVE in the layer.
  94392. */
  94393. _this.outerGlow = true;
  94394. /**
  94395. * An event triggered when the highlight layer is being blurred.
  94396. */
  94397. _this.onBeforeBlurObservable = new BABYLON.Observable();
  94398. /**
  94399. * An event triggered when the highlight layer has been blurred.
  94400. */
  94401. _this.onAfterBlurObservable = new BABYLON.Observable();
  94402. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  94403. _this._meshes = {};
  94404. _this._excludedMeshes = {};
  94405. _this.neutralColor = HighlightLayer.NeutralColor;
  94406. // Warn on stencil
  94407. if (!_this._engine.isStencilEnable) {
  94408. 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 }");
  94409. }
  94410. // Adapt options
  94411. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94412. // Initialize the layer
  94413. _this._init({
  94414. alphaBlendingMode: _this._options.alphaBlendingMode,
  94415. camera: _this._options.camera,
  94416. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94417. mainTextureRatio: _this._options.mainTextureRatio
  94418. });
  94419. // Do not render as long as no meshes have been added
  94420. _this._shouldRender = false;
  94421. return _this;
  94422. }
  94423. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  94424. /**
  94425. * Gets the horizontal size of the blur.
  94426. */
  94427. get: function () {
  94428. return this._horizontalBlurPostprocess.kernel;
  94429. },
  94430. /**
  94431. * Specifies the horizontal size of the blur.
  94432. */
  94433. set: function (value) {
  94434. this._horizontalBlurPostprocess.kernel = value;
  94435. },
  94436. enumerable: true,
  94437. configurable: true
  94438. });
  94439. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  94440. /**
  94441. * Gets the vertical size of the blur.
  94442. */
  94443. get: function () {
  94444. return this._verticalBlurPostprocess.kernel;
  94445. },
  94446. /**
  94447. * Specifies the vertical size of the blur.
  94448. */
  94449. set: function (value) {
  94450. this._verticalBlurPostprocess.kernel = value;
  94451. },
  94452. enumerable: true,
  94453. configurable: true
  94454. });
  94455. /**
  94456. * Get the effect name of the layer.
  94457. * @return The effect name
  94458. */
  94459. HighlightLayer.prototype.getEffectName = function () {
  94460. return HighlightLayer.EffectName;
  94461. };
  94462. /**
  94463. * Create the merge effect. This is the shader use to blit the information back
  94464. * to the main canvas at the end of the scene rendering.
  94465. */
  94466. HighlightLayer.prototype._createMergeEffect = function () {
  94467. // Effect
  94468. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  94469. };
  94470. /**
  94471. * Creates the render target textures and post processes used in the highlight layer.
  94472. */
  94473. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  94474. var _this = this;
  94475. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  94476. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  94477. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94478. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94479. var textureType = 0;
  94480. if (this._engine.getCaps().textureHalfFloatRender) {
  94481. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94482. }
  94483. else {
  94484. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94485. }
  94486. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  94487. width: blurTextureWidth,
  94488. height: blurTextureHeight
  94489. }, this._scene, false, true, textureType);
  94490. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94491. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94492. this._blurTexture.anisotropicFilteringLevel = 16;
  94493. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  94494. this._blurTexture.renderParticles = false;
  94495. this._blurTexture.ignoreCameraViewport = true;
  94496. this._textures = [this._blurTexture];
  94497. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  94498. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94499. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  94500. effect.setTexture("textureSampler", _this._mainTexture);
  94501. });
  94502. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94503. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94504. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94505. });
  94506. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94507. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  94508. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94509. });
  94510. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94511. }
  94512. else {
  94513. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  94514. width: blurTextureWidth,
  94515. height: blurTextureHeight
  94516. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94517. this._horizontalBlurPostprocess.width = blurTextureWidth;
  94518. this._horizontalBlurPostprocess.height = blurTextureHeight;
  94519. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94520. effect.setTexture("textureSampler", _this._mainTexture);
  94521. });
  94522. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  94523. width: blurTextureWidth,
  94524. height: blurTextureHeight
  94525. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94526. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94527. }
  94528. this._mainTexture.onAfterUnbindObservable.add(function () {
  94529. _this.onBeforeBlurObservable.notifyObservers(_this);
  94530. var internalTexture = _this._blurTexture.getInternalTexture();
  94531. if (internalTexture) {
  94532. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  94533. }
  94534. _this.onAfterBlurObservable.notifyObservers(_this);
  94535. });
  94536. // Prevent autoClear.
  94537. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94538. };
  94539. /**
  94540. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94541. */
  94542. HighlightLayer.prototype.needStencil = function () {
  94543. return true;
  94544. };
  94545. /**
  94546. * Checks for the readiness of the element composing the layer.
  94547. * @param subMesh the mesh to check for
  94548. * @param useInstances specify wether or not to use instances to render the mesh
  94549. * @param emissiveTexture the associated emissive texture used to generate the glow
  94550. * @return true if ready otherwise, false
  94551. */
  94552. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  94553. var material = subMesh.getMaterial();
  94554. var mesh = subMesh.getRenderingMesh();
  94555. if (!material || !mesh || !this._meshes) {
  94556. return false;
  94557. }
  94558. var emissiveTexture = null;
  94559. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94560. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94561. emissiveTexture = material.emissiveTexture;
  94562. }
  94563. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94564. };
  94565. /**
  94566. * Implementation specific of rendering the generating effect on the main canvas.
  94567. * @param effect The effect used to render through
  94568. */
  94569. HighlightLayer.prototype._internalRender = function (effect) {
  94570. // Texture
  94571. effect.setTexture("textureSampler", this._blurTexture);
  94572. // Cache
  94573. var engine = this._engine;
  94574. var previousStencilBuffer = engine.getStencilBuffer();
  94575. var previousStencilFunction = engine.getStencilFunction();
  94576. var previousStencilMask = engine.getStencilMask();
  94577. var previousStencilOperationPass = engine.getStencilOperationPass();
  94578. var previousStencilOperationFail = engine.getStencilOperationFail();
  94579. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  94580. var previousStencilReference = engine.getStencilFunctionReference();
  94581. // Stencil operations
  94582. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  94583. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  94584. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  94585. // Draw order
  94586. engine.setStencilMask(0x00);
  94587. engine.setStencilBuffer(true);
  94588. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  94589. // 2 passes inner outer
  94590. if (this.outerGlow) {
  94591. effect.setFloat("offset", 0);
  94592. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  94593. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94594. }
  94595. if (this.innerGlow) {
  94596. effect.setFloat("offset", 1);
  94597. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  94598. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94599. }
  94600. // Restore Cache
  94601. engine.setStencilFunction(previousStencilFunction);
  94602. engine.setStencilMask(previousStencilMask);
  94603. engine.setStencilBuffer(previousStencilBuffer);
  94604. engine.setStencilOperationPass(previousStencilOperationPass);
  94605. engine.setStencilOperationFail(previousStencilOperationFail);
  94606. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  94607. engine.setStencilFunctionReference(previousStencilReference);
  94608. };
  94609. /**
  94610. * Returns true if the layer contains information to display, otherwise false.
  94611. */
  94612. HighlightLayer.prototype.shouldRender = function () {
  94613. if (_super.prototype.shouldRender.call(this)) {
  94614. return this._meshes ? true : false;
  94615. }
  94616. return false;
  94617. };
  94618. /**
  94619. * Returns true if the mesh should render, otherwise false.
  94620. * @param mesh The mesh to render
  94621. * @returns true if it should render otherwise false
  94622. */
  94623. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  94624. // Excluded Mesh
  94625. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  94626. return false;
  94627. }
  94628. ;
  94629. return true;
  94630. };
  94631. /**
  94632. * Sets the required values for both the emissive texture and and the main color.
  94633. */
  94634. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94635. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94636. if (highlightLayerMesh) {
  94637. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  94638. }
  94639. else {
  94640. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94641. }
  94642. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94643. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94644. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  94645. }
  94646. else {
  94647. this._emissiveTextureAndColor.texture = null;
  94648. }
  94649. };
  94650. /**
  94651. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  94652. * @param mesh The mesh to exclude from the highlight layer
  94653. */
  94654. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  94655. if (!this._excludedMeshes) {
  94656. return;
  94657. }
  94658. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94659. if (!meshExcluded) {
  94660. this._excludedMeshes[mesh.uniqueId] = {
  94661. mesh: mesh,
  94662. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  94663. mesh.getEngine().setStencilBuffer(false);
  94664. }),
  94665. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  94666. mesh.getEngine().setStencilBuffer(true);
  94667. }),
  94668. };
  94669. }
  94670. };
  94671. /**
  94672. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  94673. * @param mesh The mesh to highlight
  94674. */
  94675. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  94676. if (!this._excludedMeshes) {
  94677. return;
  94678. }
  94679. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94680. if (meshExcluded) {
  94681. if (meshExcluded.beforeRender) {
  94682. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  94683. }
  94684. if (meshExcluded.afterRender) {
  94685. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  94686. }
  94687. }
  94688. this._excludedMeshes[mesh.uniqueId] = null;
  94689. };
  94690. /**
  94691. * Determine if a given mesh will be highlighted by the current HighlightLayer
  94692. * @param mesh mesh to test
  94693. * @returns true if the mesh will be highlighted by the current HighlightLayer
  94694. */
  94695. HighlightLayer.prototype.hasMesh = function (mesh) {
  94696. if (!this._meshes) {
  94697. return false;
  94698. }
  94699. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  94700. };
  94701. /**
  94702. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  94703. * @param mesh The mesh to highlight
  94704. * @param color The color of the highlight
  94705. * @param glowEmissiveOnly Extract the glow from the emissive texture
  94706. */
  94707. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  94708. var _this = this;
  94709. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  94710. if (!this._meshes) {
  94711. return;
  94712. }
  94713. var meshHighlight = this._meshes[mesh.uniqueId];
  94714. if (meshHighlight) {
  94715. meshHighlight.color = color;
  94716. }
  94717. else {
  94718. this._meshes[mesh.uniqueId] = {
  94719. mesh: mesh,
  94720. color: color,
  94721. // Lambda required for capture due to Observable this context
  94722. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  94723. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  94724. _this._defaultStencilReference(mesh);
  94725. }
  94726. else {
  94727. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  94728. }
  94729. }),
  94730. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  94731. glowEmissiveOnly: glowEmissiveOnly
  94732. };
  94733. }
  94734. this._shouldRender = true;
  94735. };
  94736. /**
  94737. * Remove a mesh from the highlight layer in order to make it stop glowing.
  94738. * @param mesh The mesh to highlight
  94739. */
  94740. HighlightLayer.prototype.removeMesh = function (mesh) {
  94741. if (!this._meshes) {
  94742. return;
  94743. }
  94744. var meshHighlight = this._meshes[mesh.uniqueId];
  94745. if (meshHighlight) {
  94746. if (meshHighlight.observerHighlight) {
  94747. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94748. }
  94749. if (meshHighlight.observerDefault) {
  94750. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94751. }
  94752. delete this._meshes[mesh.uniqueId];
  94753. }
  94754. this._shouldRender = false;
  94755. for (var meshHighlightToCheck in this._meshes) {
  94756. if (this._meshes[meshHighlightToCheck]) {
  94757. this._shouldRender = true;
  94758. break;
  94759. }
  94760. }
  94761. };
  94762. /**
  94763. * Force the stencil to the normal expected value for none glowing parts
  94764. */
  94765. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  94766. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  94767. };
  94768. /**
  94769. * Free any resources and references associated to a mesh.
  94770. * Internal use
  94771. * @param mesh The mesh to free.
  94772. */
  94773. HighlightLayer.prototype._disposeMesh = function (mesh) {
  94774. this.removeMesh(mesh);
  94775. this.removeExcludedMesh(mesh);
  94776. };
  94777. /**
  94778. * Dispose the highlight layer and free resources.
  94779. */
  94780. HighlightLayer.prototype.dispose = function () {
  94781. if (this._meshes) {
  94782. // Clean mesh references
  94783. for (var id in this._meshes) {
  94784. var meshHighlight = this._meshes[id];
  94785. if (meshHighlight && meshHighlight.mesh) {
  94786. if (meshHighlight.observerHighlight) {
  94787. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94788. }
  94789. if (meshHighlight.observerDefault) {
  94790. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94791. }
  94792. }
  94793. }
  94794. this._meshes = null;
  94795. }
  94796. if (this._excludedMeshes) {
  94797. for (var id in this._excludedMeshes) {
  94798. var meshHighlight = this._excludedMeshes[id];
  94799. if (meshHighlight) {
  94800. if (meshHighlight.beforeRender) {
  94801. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  94802. }
  94803. if (meshHighlight.afterRender) {
  94804. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  94805. }
  94806. }
  94807. }
  94808. this._excludedMeshes = null;
  94809. }
  94810. _super.prototype.dispose.call(this);
  94811. };
  94812. /**
  94813. * Gets the class name of the effect layer
  94814. * @returns the string with the class name of the effect layer
  94815. */
  94816. HighlightLayer.prototype.getClassName = function () {
  94817. return "HighlightLayer";
  94818. };
  94819. /**
  94820. * Serializes this Highlight layer
  94821. * @returns a serialized Highlight layer object
  94822. */
  94823. HighlightLayer.prototype.serialize = function () {
  94824. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94825. serializationObject.customType = "BABYLON.HighlightLayer";
  94826. // Highlighted meshes
  94827. serializationObject.meshes = [];
  94828. if (this._meshes) {
  94829. for (var m in this._meshes) {
  94830. var mesh = this._meshes[m];
  94831. if (mesh) {
  94832. serializationObject.meshes.push({
  94833. glowEmissiveOnly: mesh.glowEmissiveOnly,
  94834. color: mesh.color.asArray(),
  94835. meshId: mesh.mesh.id
  94836. });
  94837. }
  94838. }
  94839. }
  94840. // Excluded meshes
  94841. serializationObject.excludedMeshes = [];
  94842. if (this._excludedMeshes) {
  94843. for (var e in this._excludedMeshes) {
  94844. var excludedMesh = this._excludedMeshes[e];
  94845. if (excludedMesh) {
  94846. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  94847. }
  94848. }
  94849. }
  94850. return serializationObject;
  94851. };
  94852. /**
  94853. * Creates a Highlight layer from parsed Highlight layer data
  94854. * @param parsedHightlightLayer defines the Highlight layer data
  94855. * @param scene defines the current scene
  94856. * @param rootUrl defines the root URL containing the Highlight layer information
  94857. * @returns a parsed Highlight layer
  94858. */
  94859. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  94860. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  94861. var index;
  94862. // Excluded meshes
  94863. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  94864. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  94865. if (mesh) {
  94866. hl.addExcludedMesh(mesh);
  94867. }
  94868. }
  94869. // Included meshes
  94870. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  94871. var highlightedMesh = parsedHightlightLayer.meshes[index];
  94872. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  94873. if (mesh) {
  94874. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  94875. }
  94876. }
  94877. return hl;
  94878. };
  94879. /**
  94880. * Effect Name of the highlight layer.
  94881. */
  94882. HighlightLayer.EffectName = "HighlightLayer";
  94883. /**
  94884. * The neutral color used during the preparation of the glow effect.
  94885. * This is black by default as the blend operation is a blend operation.
  94886. */
  94887. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  94888. /**
  94889. * Stencil value used for glowing meshes.
  94890. */
  94891. HighlightLayer.GlowingMeshStencilReference = 0x02;
  94892. /**
  94893. * Stencil value used for the other meshes in the scene.
  94894. */
  94895. HighlightLayer.NormalMeshStencilReference = 0x01;
  94896. __decorate([
  94897. BABYLON.serialize()
  94898. ], HighlightLayer.prototype, "innerGlow", void 0);
  94899. __decorate([
  94900. BABYLON.serialize()
  94901. ], HighlightLayer.prototype, "outerGlow", void 0);
  94902. __decorate([
  94903. BABYLON.serialize()
  94904. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  94905. __decorate([
  94906. BABYLON.serialize()
  94907. ], HighlightLayer.prototype, "blurVerticalSize", null);
  94908. __decorate([
  94909. BABYLON.serialize("options")
  94910. ], HighlightLayer.prototype, "_options", void 0);
  94911. return HighlightLayer;
  94912. }(BABYLON.EffectLayer));
  94913. BABYLON.HighlightLayer = HighlightLayer;
  94914. })(BABYLON || (BABYLON = {}));
  94915. //# sourceMappingURL=babylon.highlightLayer.js.map
  94916. var BABYLON;
  94917. (function (BABYLON) {
  94918. /**
  94919. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  94920. *
  94921. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94922. * glowy meshes to your scene.
  94923. *
  94924. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  94925. */
  94926. var GlowLayer = /** @class */ (function (_super) {
  94927. __extends(GlowLayer, _super);
  94928. /**
  94929. * Instantiates a new glow Layer and references it to the scene.
  94930. * @param name The name of the layer
  94931. * @param scene The scene to use the layer in
  94932. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  94933. */
  94934. function GlowLayer(name, scene, options) {
  94935. var _this = _super.call(this, name, scene) || this;
  94936. _this._intensity = 1.0;
  94937. _this._includedOnlyMeshes = [];
  94938. _this._excludedMeshes = [];
  94939. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  94940. // Adapt options
  94941. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  94942. // Initialize the layer
  94943. _this._init({
  94944. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  94945. camera: _this._options.camera,
  94946. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94947. mainTextureRatio: _this._options.mainTextureRatio
  94948. });
  94949. return _this;
  94950. }
  94951. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  94952. /**
  94953. * Gets the kernel size of the blur.
  94954. */
  94955. get: function () {
  94956. return this._horizontalBlurPostprocess1.kernel;
  94957. },
  94958. /**
  94959. * Sets the kernel size of the blur.
  94960. */
  94961. set: function (value) {
  94962. this._horizontalBlurPostprocess1.kernel = value;
  94963. this._verticalBlurPostprocess1.kernel = value;
  94964. this._horizontalBlurPostprocess2.kernel = value;
  94965. this._verticalBlurPostprocess2.kernel = value;
  94966. },
  94967. enumerable: true,
  94968. configurable: true
  94969. });
  94970. Object.defineProperty(GlowLayer.prototype, "intensity", {
  94971. /**
  94972. * Gets the glow intensity.
  94973. */
  94974. get: function () {
  94975. return this._intensity;
  94976. },
  94977. /**
  94978. * Sets the glow intensity.
  94979. */
  94980. set: function (value) {
  94981. this._intensity = value;
  94982. },
  94983. enumerable: true,
  94984. configurable: true
  94985. });
  94986. /**
  94987. * Get the effect name of the layer.
  94988. * @return The effect name
  94989. */
  94990. GlowLayer.prototype.getEffectName = function () {
  94991. return GlowLayer.EffectName;
  94992. };
  94993. /**
  94994. * Create the merge effect. This is the shader use to blit the information back
  94995. * to the main canvas at the end of the scene rendering.
  94996. */
  94997. GlowLayer.prototype._createMergeEffect = function () {
  94998. // Effect
  94999. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  95000. };
  95001. /**
  95002. * Creates the render target textures and post processes used in the glow layer.
  95003. */
  95004. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  95005. var _this = this;
  95006. var blurTextureWidth = this._mainTextureDesiredSize.width;
  95007. var blurTextureHeight = this._mainTextureDesiredSize.height;
  95008. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95009. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95010. var textureType = 0;
  95011. if (this._engine.getCaps().textureHalfFloatRender) {
  95012. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95013. }
  95014. else {
  95015. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95016. }
  95017. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  95018. width: blurTextureWidth,
  95019. height: blurTextureHeight
  95020. }, this._scene, false, true, textureType);
  95021. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95022. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95023. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95024. this._blurTexture1.renderParticles = false;
  95025. this._blurTexture1.ignoreCameraViewport = true;
  95026. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  95027. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  95028. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  95029. width: blurTextureWidth2,
  95030. height: blurTextureHeight2
  95031. }, this._scene, false, true, textureType);
  95032. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95033. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95034. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95035. this._blurTexture2.renderParticles = false;
  95036. this._blurTexture2.ignoreCameraViewport = true;
  95037. this._textures = [this._blurTexture1, this._blurTexture2];
  95038. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95039. width: blurTextureWidth,
  95040. height: blurTextureHeight
  95041. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95042. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  95043. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  95044. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  95045. effect.setTexture("textureSampler", _this._mainTexture);
  95046. });
  95047. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95048. width: blurTextureWidth,
  95049. height: blurTextureHeight
  95050. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95051. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95052. width: blurTextureWidth2,
  95053. height: blurTextureHeight2
  95054. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95055. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  95056. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  95057. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  95058. effect.setTexture("textureSampler", _this._blurTexture1);
  95059. });
  95060. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95061. width: blurTextureWidth2,
  95062. height: blurTextureHeight2
  95063. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95064. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95065. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  95066. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95067. this._mainTexture.samples = this._options.mainTextureSamples;
  95068. this._mainTexture.onAfterUnbindObservable.add(function () {
  95069. var internalTexture = _this._blurTexture1.getInternalTexture();
  95070. if (internalTexture) {
  95071. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  95072. internalTexture = _this._blurTexture2.getInternalTexture();
  95073. if (internalTexture) {
  95074. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  95075. }
  95076. }
  95077. });
  95078. // Prevent autoClear.
  95079. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95080. };
  95081. /**
  95082. * Checks for the readiness of the element composing the layer.
  95083. * @param subMesh the mesh to check for
  95084. * @param useInstances specify wether or not to use instances to render the mesh
  95085. * @param emissiveTexture the associated emissive texture used to generate the glow
  95086. * @return true if ready otherwise, false
  95087. */
  95088. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  95089. var material = subMesh.getMaterial();
  95090. var mesh = subMesh.getRenderingMesh();
  95091. if (!material || !mesh) {
  95092. return false;
  95093. }
  95094. var emissiveTexture = material.emissiveTexture;
  95095. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95096. };
  95097. /**
  95098. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95099. */
  95100. GlowLayer.prototype.needStencil = function () {
  95101. return false;
  95102. };
  95103. /**
  95104. * Implementation specific of rendering the generating effect on the main canvas.
  95105. * @param effect The effect used to render through
  95106. */
  95107. GlowLayer.prototype._internalRender = function (effect) {
  95108. // Texture
  95109. effect.setTexture("textureSampler", this._blurTexture1);
  95110. effect.setTexture("textureSampler2", this._blurTexture2);
  95111. effect.setFloat("offset", this._intensity);
  95112. // Cache
  95113. var engine = this._engine;
  95114. var previousStencilBuffer = engine.getStencilBuffer();
  95115. // Draw order
  95116. engine.setStencilBuffer(false);
  95117. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95118. // Draw order
  95119. engine.setStencilBuffer(previousStencilBuffer);
  95120. };
  95121. /**
  95122. * Sets the required values for both the emissive texture and and the main color.
  95123. */
  95124. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  95125. var textureLevel = 1.0;
  95126. if (this.customEmissiveTextureSelector) {
  95127. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  95128. }
  95129. else {
  95130. if (material) {
  95131. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  95132. if (this._emissiveTextureAndColor.texture) {
  95133. textureLevel = this._emissiveTextureAndColor.texture.level;
  95134. }
  95135. }
  95136. else {
  95137. this._emissiveTextureAndColor.texture = null;
  95138. }
  95139. }
  95140. if (this.customEmissiveColorSelector) {
  95141. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  95142. }
  95143. else {
  95144. if (material.emissiveColor) {
  95145. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  95146. }
  95147. else {
  95148. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  95149. }
  95150. }
  95151. };
  95152. /**
  95153. * Returns true if the mesh should render, otherwise false.
  95154. * @param mesh The mesh to render
  95155. * @returns true if it should render otherwise false
  95156. */
  95157. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  95158. return this.hasMesh(mesh);
  95159. };
  95160. /**
  95161. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  95162. * @param mesh The mesh to exclude from the glow layer
  95163. */
  95164. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  95165. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  95166. this._excludedMeshes.push(mesh.uniqueId);
  95167. }
  95168. };
  95169. /**
  95170. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  95171. * @param mesh The mesh to remove
  95172. */
  95173. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  95174. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  95175. if (index !== -1) {
  95176. this._excludedMeshes.splice(index, 1);
  95177. }
  95178. };
  95179. /**
  95180. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  95181. * @param mesh The mesh to include in the glow layer
  95182. */
  95183. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  95184. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  95185. this._includedOnlyMeshes.push(mesh.uniqueId);
  95186. }
  95187. };
  95188. /**
  95189. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  95190. * @param mesh The mesh to remove
  95191. */
  95192. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  95193. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  95194. if (index !== -1) {
  95195. this._includedOnlyMeshes.splice(index, 1);
  95196. }
  95197. };
  95198. /**
  95199. * Determine if a given mesh will be used in the glow layer
  95200. * @param mesh The mesh to test
  95201. * @returns true if the mesh will be highlighted by the current glow layer
  95202. */
  95203. GlowLayer.prototype.hasMesh = function (mesh) {
  95204. // Included Mesh
  95205. if (this._includedOnlyMeshes.length) {
  95206. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  95207. }
  95208. ;
  95209. // Excluded Mesh
  95210. if (this._excludedMeshes.length) {
  95211. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  95212. }
  95213. ;
  95214. return true;
  95215. };
  95216. /**
  95217. * Free any resources and references associated to a mesh.
  95218. * Internal use
  95219. * @param mesh The mesh to free.
  95220. */
  95221. GlowLayer.prototype._disposeMesh = function (mesh) {
  95222. this.removeIncludedOnlyMesh(mesh);
  95223. this.removeExcludedMesh(mesh);
  95224. };
  95225. /**
  95226. * Gets the class name of the effect layer
  95227. * @returns the string with the class name of the effect layer
  95228. */
  95229. GlowLayer.prototype.getClassName = function () {
  95230. return "GlowLayer";
  95231. };
  95232. /**
  95233. * Serializes this glow layer
  95234. * @returns a serialized glow layer object
  95235. */
  95236. GlowLayer.prototype.serialize = function () {
  95237. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95238. serializationObject.customType = "BABYLON.GlowLayer";
  95239. var index;
  95240. // Included meshes
  95241. serializationObject.includedMeshes = [];
  95242. if (this._includedOnlyMeshes.length) {
  95243. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  95244. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  95245. if (mesh) {
  95246. serializationObject.includedMeshes.push(mesh.id);
  95247. }
  95248. }
  95249. }
  95250. // Excluded meshes
  95251. serializationObject.excludedMeshes = [];
  95252. if (this._excludedMeshes.length) {
  95253. for (index = 0; index < this._excludedMeshes.length; index++) {
  95254. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  95255. if (mesh) {
  95256. serializationObject.excludedMeshes.push(mesh.id);
  95257. }
  95258. }
  95259. }
  95260. return serializationObject;
  95261. };
  95262. /**
  95263. * Creates a Glow Layer from parsed glow layer data
  95264. * @param parsedGlowLayer defines glow layer data
  95265. * @param scene defines the current scene
  95266. * @param rootUrl defines the root URL containing the glow layer information
  95267. * @returns a parsed Glow Layer
  95268. */
  95269. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  95270. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  95271. var index;
  95272. // Excluded meshes
  95273. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  95274. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  95275. if (mesh) {
  95276. gl.addExcludedMesh(mesh);
  95277. }
  95278. }
  95279. // Included meshes
  95280. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  95281. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  95282. if (mesh) {
  95283. gl.addIncludedOnlyMesh(mesh);
  95284. }
  95285. }
  95286. return gl;
  95287. };
  95288. /**
  95289. * Effect Name of the layer.
  95290. */
  95291. GlowLayer.EffectName = "GlowLayer";
  95292. /**
  95293. * The default blur kernel size used for the glow.
  95294. */
  95295. GlowLayer.DefaultBlurKernelSize = 32;
  95296. /**
  95297. * The default texture size ratio used for the glow.
  95298. */
  95299. GlowLayer.DefaultTextureRatio = 0.5;
  95300. __decorate([
  95301. BABYLON.serialize()
  95302. ], GlowLayer.prototype, "blurKernelSize", null);
  95303. __decorate([
  95304. BABYLON.serialize()
  95305. ], GlowLayer.prototype, "intensity", null);
  95306. __decorate([
  95307. BABYLON.serialize("options")
  95308. ], GlowLayer.prototype, "_options", void 0);
  95309. return GlowLayer;
  95310. }(BABYLON.EffectLayer));
  95311. BABYLON.GlowLayer = GlowLayer;
  95312. })(BABYLON || (BABYLON = {}));
  95313. //# sourceMappingURL=babylon.glowLayer.js.map
  95314. var BABYLON;
  95315. (function (BABYLON) {
  95316. /**
  95317. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  95318. */
  95319. var AssetTaskState;
  95320. (function (AssetTaskState) {
  95321. /**
  95322. * Initialization
  95323. */
  95324. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  95325. /**
  95326. * Running
  95327. */
  95328. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  95329. /**
  95330. * Done
  95331. */
  95332. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  95333. /**
  95334. * Error
  95335. */
  95336. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  95337. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  95338. /**
  95339. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  95340. */
  95341. var AbstractAssetTask = /** @class */ (function () {
  95342. /**
  95343. * Creates a new {BABYLON.AssetsManager}
  95344. * @param name defines the name of the task
  95345. */
  95346. function AbstractAssetTask(
  95347. /**
  95348. * Task name
  95349. */ name) {
  95350. this.name = name;
  95351. this._isCompleted = false;
  95352. this._taskState = AssetTaskState.INIT;
  95353. }
  95354. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  95355. /**
  95356. * Get if the task is completed
  95357. */
  95358. get: function () {
  95359. return this._isCompleted;
  95360. },
  95361. enumerable: true,
  95362. configurable: true
  95363. });
  95364. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  95365. /**
  95366. * Gets the current state of the task
  95367. */
  95368. get: function () {
  95369. return this._taskState;
  95370. },
  95371. enumerable: true,
  95372. configurable: true
  95373. });
  95374. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  95375. /**
  95376. * Gets the current error object (if task is in error)
  95377. */
  95378. get: function () {
  95379. return this._errorObject;
  95380. },
  95381. enumerable: true,
  95382. configurable: true
  95383. });
  95384. /**
  95385. * Internal only
  95386. * @hidden
  95387. */
  95388. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  95389. if (this._errorObject) {
  95390. return;
  95391. }
  95392. this._errorObject = {
  95393. message: message,
  95394. exception: exception
  95395. };
  95396. };
  95397. /**
  95398. * Execute the current task
  95399. * @param scene defines the scene where you want your assets to be loaded
  95400. * @param onSuccess is a callback called when the task is successfully executed
  95401. * @param onError is a callback called if an error occurs
  95402. */
  95403. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95404. var _this = this;
  95405. this._taskState = AssetTaskState.RUNNING;
  95406. this.runTask(scene, function () {
  95407. _this.onDoneCallback(onSuccess, onError);
  95408. }, function (msg, exception) {
  95409. _this.onErrorCallback(onError, msg, exception);
  95410. });
  95411. };
  95412. /**
  95413. * Execute the current task
  95414. * @param scene defines the scene where you want your assets to be loaded
  95415. * @param onSuccess is a callback called when the task is successfully executed
  95416. * @param onError is a callback called if an error occurs
  95417. */
  95418. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95419. throw new Error("runTask is not implemented");
  95420. };
  95421. /**
  95422. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  95423. * This can be used with failed tasks that have the reason for failure fixed.
  95424. */
  95425. AbstractAssetTask.prototype.reset = function () {
  95426. this._taskState = AssetTaskState.INIT;
  95427. };
  95428. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  95429. this._taskState = AssetTaskState.ERROR;
  95430. this._errorObject = {
  95431. message: message,
  95432. exception: exception
  95433. };
  95434. if (this.onError) {
  95435. this.onError(this, message, exception);
  95436. }
  95437. onError();
  95438. };
  95439. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  95440. try {
  95441. this._taskState = AssetTaskState.DONE;
  95442. this._isCompleted = true;
  95443. if (this.onSuccess) {
  95444. this.onSuccess(this);
  95445. }
  95446. onSuccess();
  95447. }
  95448. catch (e) {
  95449. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  95450. }
  95451. };
  95452. return AbstractAssetTask;
  95453. }());
  95454. BABYLON.AbstractAssetTask = AbstractAssetTask;
  95455. /**
  95456. * Class used to share progress information about assets loading
  95457. */
  95458. var AssetsProgressEvent = /** @class */ (function () {
  95459. /**
  95460. * Creates a {BABYLON.AssetsProgressEvent}
  95461. * @param remainingCount defines the number of remaining tasks to process
  95462. * @param totalCount defines the total number of tasks
  95463. * @param task defines the task that was just processed
  95464. */
  95465. function AssetsProgressEvent(remainingCount, totalCount, task) {
  95466. this.remainingCount = remainingCount;
  95467. this.totalCount = totalCount;
  95468. this.task = task;
  95469. }
  95470. return AssetsProgressEvent;
  95471. }());
  95472. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  95473. /**
  95474. * Define a task used by {BABYLON.AssetsManager} to load meshes
  95475. */
  95476. var MeshAssetTask = /** @class */ (function (_super) {
  95477. __extends(MeshAssetTask, _super);
  95478. /**
  95479. * Creates a new {BABYLON.MeshAssetTask}
  95480. * @param name defines the name of the task
  95481. * @param meshesNames defines the list of mesh's names you want to load
  95482. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  95483. * @param sceneFilename defines the filename of the scene to load from
  95484. */
  95485. function MeshAssetTask(
  95486. /**
  95487. * Defines the name of the task
  95488. */
  95489. name,
  95490. /**
  95491. * Defines the list of mesh's names you want to load
  95492. */
  95493. meshesNames,
  95494. /**
  95495. * Defines the root url to use as a base to load your meshes and associated resources
  95496. */
  95497. rootUrl,
  95498. /**
  95499. * Defines the filename of the scene to load from
  95500. */
  95501. sceneFilename) {
  95502. var _this = _super.call(this, name) || this;
  95503. _this.name = name;
  95504. _this.meshesNames = meshesNames;
  95505. _this.rootUrl = rootUrl;
  95506. _this.sceneFilename = sceneFilename;
  95507. return _this;
  95508. }
  95509. /**
  95510. * Execute the current task
  95511. * @param scene defines the scene where you want your assets to be loaded
  95512. * @param onSuccess is a callback called when the task is successfully executed
  95513. * @param onError is a callback called if an error occurs
  95514. */
  95515. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95516. var _this = this;
  95517. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  95518. _this.loadedMeshes = meshes;
  95519. _this.loadedParticleSystems = particleSystems;
  95520. _this.loadedSkeletons = skeletons;
  95521. onSuccess();
  95522. }, null, function (scene, message, exception) {
  95523. onError(message, exception);
  95524. });
  95525. };
  95526. return MeshAssetTask;
  95527. }(AbstractAssetTask));
  95528. BABYLON.MeshAssetTask = MeshAssetTask;
  95529. /**
  95530. * Define a task used by {BABYLON.AssetsManager} to load text content
  95531. */
  95532. var TextFileAssetTask = /** @class */ (function (_super) {
  95533. __extends(TextFileAssetTask, _super);
  95534. /**
  95535. * Creates a new TextFileAssetTask object
  95536. * @param name defines the name of the task
  95537. * @param url defines the location of the file to load
  95538. */
  95539. function TextFileAssetTask(
  95540. /**
  95541. * Defines the name of the task
  95542. */
  95543. name,
  95544. /**
  95545. * Defines the location of the file to load
  95546. */
  95547. url) {
  95548. var _this = _super.call(this, name) || this;
  95549. _this.name = name;
  95550. _this.url = url;
  95551. return _this;
  95552. }
  95553. /**
  95554. * Execute the current task
  95555. * @param scene defines the scene where you want your assets to be loaded
  95556. * @param onSuccess is a callback called when the task is successfully executed
  95557. * @param onError is a callback called if an error occurs
  95558. */
  95559. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95560. var _this = this;
  95561. scene._loadFile(this.url, function (data) {
  95562. _this.text = data;
  95563. onSuccess();
  95564. }, undefined, false, false, function (request, exception) {
  95565. if (request) {
  95566. onError(request.status + " " + request.statusText, exception);
  95567. }
  95568. });
  95569. };
  95570. return TextFileAssetTask;
  95571. }(AbstractAssetTask));
  95572. BABYLON.TextFileAssetTask = TextFileAssetTask;
  95573. /**
  95574. * Define a task used by {BABYLON.AssetsManager} to load binary data
  95575. */
  95576. var BinaryFileAssetTask = /** @class */ (function (_super) {
  95577. __extends(BinaryFileAssetTask, _super);
  95578. /**
  95579. * Creates a new BinaryFileAssetTask object
  95580. * @param name defines the name of the new task
  95581. * @param url defines the location of the file to load
  95582. */
  95583. function BinaryFileAssetTask(
  95584. /**
  95585. * Defines the name of the task
  95586. */
  95587. name,
  95588. /**
  95589. * Defines the location of the file to load
  95590. */
  95591. url) {
  95592. var _this = _super.call(this, name) || this;
  95593. _this.name = name;
  95594. _this.url = url;
  95595. return _this;
  95596. }
  95597. /**
  95598. * Execute the current task
  95599. * @param scene defines the scene where you want your assets to be loaded
  95600. * @param onSuccess is a callback called when the task is successfully executed
  95601. * @param onError is a callback called if an error occurs
  95602. */
  95603. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95604. var _this = this;
  95605. scene._loadFile(this.url, function (data) {
  95606. _this.data = data;
  95607. onSuccess();
  95608. }, undefined, true, true, function (request, exception) {
  95609. if (request) {
  95610. onError(request.status + " " + request.statusText, exception);
  95611. }
  95612. });
  95613. };
  95614. return BinaryFileAssetTask;
  95615. }(AbstractAssetTask));
  95616. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  95617. /**
  95618. * Define a task used by {BABYLON.AssetsManager} to load images
  95619. */
  95620. var ImageAssetTask = /** @class */ (function (_super) {
  95621. __extends(ImageAssetTask, _super);
  95622. /**
  95623. * Creates a new ImageAssetTask
  95624. * @param name defines the name of the task
  95625. * @param url defines the location of the image to load
  95626. */
  95627. function ImageAssetTask(
  95628. /**
  95629. * Defines the name of the task
  95630. */
  95631. name,
  95632. /**
  95633. * Defines the location of the image to load
  95634. */
  95635. url) {
  95636. var _this = _super.call(this, name) || this;
  95637. _this.name = name;
  95638. _this.url = url;
  95639. return _this;
  95640. }
  95641. /**
  95642. * Execute the current task
  95643. * @param scene defines the scene where you want your assets to be loaded
  95644. * @param onSuccess is a callback called when the task is successfully executed
  95645. * @param onError is a callback called if an error occurs
  95646. */
  95647. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95648. var _this = this;
  95649. var img = new Image();
  95650. BABYLON.Tools.SetCorsBehavior(this.url, img);
  95651. img.onload = function () {
  95652. _this.image = img;
  95653. onSuccess();
  95654. };
  95655. img.onerror = function (err) {
  95656. onError("Error loading image", err);
  95657. };
  95658. img.src = this.url;
  95659. };
  95660. return ImageAssetTask;
  95661. }(AbstractAssetTask));
  95662. BABYLON.ImageAssetTask = ImageAssetTask;
  95663. /**
  95664. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  95665. */
  95666. var TextureAssetTask = /** @class */ (function (_super) {
  95667. __extends(TextureAssetTask, _super);
  95668. /**
  95669. * Creates a new TextureAssetTask object
  95670. * @param name defines the name of the task
  95671. * @param url defines the location of the file to load
  95672. * @param noMipmap defines if mipmap should not be generated (default is false)
  95673. * @param invertY defines if texture must be inverted on Y axis (default is false)
  95674. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95675. */
  95676. function TextureAssetTask(
  95677. /**
  95678. * Defines the name of the task
  95679. */
  95680. name,
  95681. /**
  95682. * Defines the location of the file to load
  95683. */
  95684. url,
  95685. /**
  95686. * Defines if mipmap should not be generated (default is false)
  95687. */
  95688. noMipmap,
  95689. /**
  95690. * Defines if texture must be inverted on Y axis (default is false)
  95691. */
  95692. invertY,
  95693. /**
  95694. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95695. */
  95696. samplingMode) {
  95697. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95698. var _this = _super.call(this, name) || this;
  95699. _this.name = name;
  95700. _this.url = url;
  95701. _this.noMipmap = noMipmap;
  95702. _this.invertY = invertY;
  95703. _this.samplingMode = samplingMode;
  95704. return _this;
  95705. }
  95706. /**
  95707. * Execute the current task
  95708. * @param scene defines the scene where you want your assets to be loaded
  95709. * @param onSuccess is a callback called when the task is successfully executed
  95710. * @param onError is a callback called if an error occurs
  95711. */
  95712. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95713. var onload = function () {
  95714. onSuccess();
  95715. };
  95716. var onerror = function (message, exception) {
  95717. onError(message, exception);
  95718. };
  95719. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  95720. };
  95721. return TextureAssetTask;
  95722. }(AbstractAssetTask));
  95723. BABYLON.TextureAssetTask = TextureAssetTask;
  95724. /**
  95725. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  95726. */
  95727. var CubeTextureAssetTask = /** @class */ (function (_super) {
  95728. __extends(CubeTextureAssetTask, _super);
  95729. /**
  95730. * Creates a new CubeTextureAssetTask
  95731. * @param name defines the name of the task
  95732. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95733. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95734. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95735. * @param files defines the explicit list of files (undefined by default)
  95736. */
  95737. function CubeTextureAssetTask(
  95738. /**
  95739. * Defines the name of the task
  95740. */
  95741. name,
  95742. /**
  95743. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95744. */
  95745. url,
  95746. /**
  95747. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95748. */
  95749. extensions,
  95750. /**
  95751. * Defines if mipmaps should not be generated (default is false)
  95752. */
  95753. noMipmap,
  95754. /**
  95755. * Defines the explicit list of files (undefined by default)
  95756. */
  95757. files) {
  95758. var _this = _super.call(this, name) || this;
  95759. _this.name = name;
  95760. _this.url = url;
  95761. _this.extensions = extensions;
  95762. _this.noMipmap = noMipmap;
  95763. _this.files = files;
  95764. return _this;
  95765. }
  95766. /**
  95767. * Execute the current task
  95768. * @param scene defines the scene where you want your assets to be loaded
  95769. * @param onSuccess is a callback called when the task is successfully executed
  95770. * @param onError is a callback called if an error occurs
  95771. */
  95772. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95773. var onload = function () {
  95774. onSuccess();
  95775. };
  95776. var onerror = function (message, exception) {
  95777. onError(message, exception);
  95778. };
  95779. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  95780. };
  95781. return CubeTextureAssetTask;
  95782. }(AbstractAssetTask));
  95783. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  95784. /**
  95785. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  95786. */
  95787. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  95788. __extends(HDRCubeTextureAssetTask, _super);
  95789. /**
  95790. * Creates a new HDRCubeTextureAssetTask object
  95791. * @param name defines the name of the task
  95792. * @param url defines the location of the file to load
  95793. * @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.
  95794. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95795. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95796. * @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)
  95797. * @param reserved Internal use only
  95798. */
  95799. function HDRCubeTextureAssetTask(
  95800. /**
  95801. * Defines the name of the task
  95802. */
  95803. name,
  95804. /**
  95805. * Defines the location of the file to load
  95806. */
  95807. url,
  95808. /**
  95809. * Defines the desired size (the more it increases the longer the generation will be)
  95810. */
  95811. size,
  95812. /**
  95813. * Defines if mipmaps should not be generated (default is false)
  95814. */
  95815. noMipmap,
  95816. /**
  95817. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95818. */
  95819. generateHarmonics,
  95820. /**
  95821. * 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)
  95822. */
  95823. gammaSpace,
  95824. /**
  95825. * Internal Use Only
  95826. */
  95827. reserved) {
  95828. if (noMipmap === void 0) { noMipmap = false; }
  95829. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95830. if (gammaSpace === void 0) { gammaSpace = false; }
  95831. if (reserved === void 0) { reserved = false; }
  95832. var _this = _super.call(this, name) || this;
  95833. _this.name = name;
  95834. _this.url = url;
  95835. _this.size = size;
  95836. _this.noMipmap = noMipmap;
  95837. _this.generateHarmonics = generateHarmonics;
  95838. _this.gammaSpace = gammaSpace;
  95839. _this.reserved = reserved;
  95840. return _this;
  95841. }
  95842. /**
  95843. * Execute the current task
  95844. * @param scene defines the scene where you want your assets to be loaded
  95845. * @param onSuccess is a callback called when the task is successfully executed
  95846. * @param onError is a callback called if an error occurs
  95847. */
  95848. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95849. var onload = function () {
  95850. onSuccess();
  95851. };
  95852. var onerror = function (message, exception) {
  95853. onError(message, exception);
  95854. };
  95855. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  95856. };
  95857. return HDRCubeTextureAssetTask;
  95858. }(AbstractAssetTask));
  95859. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  95860. /**
  95861. * This class can be used to easily import assets into a scene
  95862. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  95863. */
  95864. var AssetsManager = /** @class */ (function () {
  95865. /**
  95866. * Creates a new AssetsManager
  95867. * @param scene defines the scene to work on
  95868. */
  95869. function AssetsManager(scene) {
  95870. this._isLoading = false;
  95871. this._tasks = new Array();
  95872. this._waitingTasksCount = 0;
  95873. this._totalTasksCount = 0;
  95874. /**
  95875. * Observable called when all tasks are processed
  95876. */
  95877. this.onTaskSuccessObservable = new BABYLON.Observable();
  95878. /**
  95879. * Observable called when a task had an error
  95880. */
  95881. this.onTaskErrorObservable = new BABYLON.Observable();
  95882. /**
  95883. * Observable called when a task is successful
  95884. */
  95885. this.onTasksDoneObservable = new BABYLON.Observable();
  95886. /**
  95887. * Observable called when a task is done (whatever the result is)
  95888. */
  95889. this.onProgressObservable = new BABYLON.Observable();
  95890. /**
  95891. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  95892. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  95893. */
  95894. this.useDefaultLoadingScreen = true;
  95895. this._scene = scene;
  95896. }
  95897. /**
  95898. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  95899. * @param taskName defines the name of the new task
  95900. * @param meshesNames defines the name of meshes to load
  95901. * @param rootUrl defines the root url to use to locate files
  95902. * @param sceneFilename defines the filename of the scene file
  95903. * @returns a new {BABYLON.MeshAssetTask} object
  95904. */
  95905. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  95906. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  95907. this._tasks.push(task);
  95908. return task;
  95909. };
  95910. /**
  95911. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  95912. * @param taskName defines the name of the new task
  95913. * @param url defines the url of the file to load
  95914. * @returns a new {BABYLON.TextFileAssetTask} object
  95915. */
  95916. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  95917. var task = new TextFileAssetTask(taskName, url);
  95918. this._tasks.push(task);
  95919. return task;
  95920. };
  95921. /**
  95922. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  95923. * @param taskName defines the name of the new task
  95924. * @param url defines the url of the file to load
  95925. * @returns a new {BABYLON.BinaryFileAssetTask} object
  95926. */
  95927. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  95928. var task = new BinaryFileAssetTask(taskName, url);
  95929. this._tasks.push(task);
  95930. return task;
  95931. };
  95932. /**
  95933. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  95934. * @param taskName defines the name of the new task
  95935. * @param url defines the url of the file to load
  95936. * @returns a new {BABYLON.ImageAssetTask} object
  95937. */
  95938. AssetsManager.prototype.addImageTask = function (taskName, url) {
  95939. var task = new ImageAssetTask(taskName, url);
  95940. this._tasks.push(task);
  95941. return task;
  95942. };
  95943. /**
  95944. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  95945. * @param taskName defines the name of the new task
  95946. * @param url defines the url of the file to load
  95947. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95948. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  95949. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  95950. * @returns a new {BABYLON.TextureAssetTask} object
  95951. */
  95952. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  95953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95954. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  95955. this._tasks.push(task);
  95956. return task;
  95957. };
  95958. /**
  95959. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  95960. * @param taskName defines the name of the new task
  95961. * @param url defines the url of the file to load
  95962. * @param extensions defines the extension to use to load the cube map (can be null)
  95963. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95964. * @param files defines the list of files to load (can be null)
  95965. * @returns a new {BABYLON.CubeTextureAssetTask} object
  95966. */
  95967. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  95968. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  95969. this._tasks.push(task);
  95970. return task;
  95971. };
  95972. /**
  95973. *
  95974. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  95975. * @param taskName defines the name of the new task
  95976. * @param url defines the url of the file to load
  95977. * @param size defines the size you want for the cubemap (can be null)
  95978. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95979. * @param generateHarmonics defines if you want to automatically generate (true by default)
  95980. * @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)
  95981. * @param reserved Internal use only
  95982. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  95983. */
  95984. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  95985. if (noMipmap === void 0) { noMipmap = false; }
  95986. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95987. if (gammaSpace === void 0) { gammaSpace = false; }
  95988. if (reserved === void 0) { reserved = false; }
  95989. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  95990. this._tasks.push(task);
  95991. return task;
  95992. };
  95993. /**
  95994. * Remove a task from the assets manager.
  95995. * @param task the task to remove
  95996. */
  95997. AssetsManager.prototype.removeTask = function (task) {
  95998. var index = this._tasks.indexOf(task);
  95999. if (index > -1) {
  96000. this._tasks.splice(index, 1);
  96001. }
  96002. };
  96003. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  96004. this._waitingTasksCount--;
  96005. try {
  96006. if (this.onProgress) {
  96007. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  96008. }
  96009. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  96010. }
  96011. catch (e) {
  96012. BABYLON.Tools.Error("Error running progress callbacks.");
  96013. console.log(e);
  96014. }
  96015. if (this._waitingTasksCount === 0) {
  96016. try {
  96017. if (this.onFinish) {
  96018. this.onFinish(this._tasks);
  96019. }
  96020. // Let's remove successfull tasks
  96021. var currentTasks = this._tasks.slice();
  96022. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  96023. var task = currentTasks_1[_i];
  96024. if (task.taskState === AssetTaskState.DONE) {
  96025. var index = this._tasks.indexOf(task);
  96026. if (index > -1) {
  96027. this._tasks.splice(index, 1);
  96028. }
  96029. }
  96030. }
  96031. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96032. }
  96033. catch (e) {
  96034. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  96035. console.log(e);
  96036. }
  96037. this._isLoading = false;
  96038. this._scene.getEngine().hideLoadingUI();
  96039. }
  96040. };
  96041. AssetsManager.prototype._runTask = function (task) {
  96042. var _this = this;
  96043. var done = function () {
  96044. try {
  96045. if (_this.onTaskSuccess) {
  96046. _this.onTaskSuccess(task);
  96047. }
  96048. _this.onTaskSuccessObservable.notifyObservers(task);
  96049. _this._decreaseWaitingTasksCount(task);
  96050. }
  96051. catch (e) {
  96052. error("Error executing task success callbacks", e);
  96053. }
  96054. };
  96055. var error = function (message, exception) {
  96056. task._setErrorObject(message, exception);
  96057. if (_this.onTaskError) {
  96058. _this.onTaskError(task);
  96059. }
  96060. _this.onTaskErrorObservable.notifyObservers(task);
  96061. _this._decreaseWaitingTasksCount(task);
  96062. };
  96063. task.run(this._scene, done, error);
  96064. };
  96065. /**
  96066. * Reset the {BABYLON.AssetsManager} and remove all tasks
  96067. * @return the current instance of the {BABYLON.AssetsManager}
  96068. */
  96069. AssetsManager.prototype.reset = function () {
  96070. this._isLoading = false;
  96071. this._tasks = new Array();
  96072. return this;
  96073. };
  96074. /**
  96075. * Start the loading process
  96076. * @return the current instance of the {BABYLON.AssetsManager}
  96077. */
  96078. AssetsManager.prototype.load = function () {
  96079. if (this._isLoading) {
  96080. return this;
  96081. }
  96082. this._isLoading = true;
  96083. this._waitingTasksCount = this._tasks.length;
  96084. this._totalTasksCount = this._tasks.length;
  96085. if (this._waitingTasksCount === 0) {
  96086. this._isLoading = false;
  96087. if (this.onFinish) {
  96088. this.onFinish(this._tasks);
  96089. }
  96090. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96091. return this;
  96092. }
  96093. if (this.useDefaultLoadingScreen) {
  96094. this._scene.getEngine().displayLoadingUI();
  96095. }
  96096. for (var index = 0; index < this._tasks.length; index++) {
  96097. var task = this._tasks[index];
  96098. if (task.taskState === AssetTaskState.INIT) {
  96099. this._runTask(task);
  96100. }
  96101. }
  96102. return this;
  96103. };
  96104. return AssetsManager;
  96105. }());
  96106. BABYLON.AssetsManager = AssetsManager;
  96107. })(BABYLON || (BABYLON = {}));
  96108. //# sourceMappingURL=babylon.assetsManager.js.map
  96109. var BABYLON;
  96110. (function (BABYLON) {
  96111. var serializedGeometries = [];
  96112. var serializeGeometry = function (geometry, serializationGeometries) {
  96113. if (serializedGeometries[geometry.id]) {
  96114. return;
  96115. }
  96116. if (geometry.doNotSerialize) {
  96117. return;
  96118. }
  96119. if (geometry instanceof BABYLON.BoxGeometry) {
  96120. serializationGeometries.boxes.push(geometry.serialize());
  96121. }
  96122. else if (geometry instanceof BABYLON.SphereGeometry) {
  96123. serializationGeometries.spheres.push(geometry.serialize());
  96124. }
  96125. else if (geometry instanceof BABYLON.CylinderGeometry) {
  96126. serializationGeometries.cylinders.push(geometry.serialize());
  96127. }
  96128. else if (geometry instanceof BABYLON.TorusGeometry) {
  96129. serializationGeometries.toruses.push(geometry.serialize());
  96130. }
  96131. else if (geometry instanceof BABYLON.GroundGeometry) {
  96132. serializationGeometries.grounds.push(geometry.serialize());
  96133. }
  96134. else if (geometry instanceof BABYLON.Plane) {
  96135. serializationGeometries.planes.push(geometry.serialize());
  96136. }
  96137. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  96138. serializationGeometries.torusKnots.push(geometry.serialize());
  96139. }
  96140. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  96141. throw new Error("Unknown primitive type");
  96142. }
  96143. else {
  96144. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  96145. }
  96146. serializedGeometries[geometry.id] = true;
  96147. };
  96148. var serializeMesh = function (mesh, serializationScene) {
  96149. var serializationObject = {};
  96150. // Geometry
  96151. var geometry = mesh._geometry;
  96152. if (geometry) {
  96153. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  96154. // 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
  96155. serializeGeometry(geometry, serializationScene.geometries);
  96156. }
  96157. }
  96158. // Custom
  96159. if (mesh.serialize) {
  96160. mesh.serialize(serializationObject);
  96161. }
  96162. return serializationObject;
  96163. };
  96164. var finalizeSingleMesh = function (mesh, serializationObject) {
  96165. //only works if the mesh is already loaded
  96166. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96167. //serialize material
  96168. if (mesh.material) {
  96169. if (mesh.material instanceof BABYLON.MultiMaterial) {
  96170. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  96171. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  96172. serializationObject.multiMaterials.push(mesh.material.serialize());
  96173. }
  96174. }
  96175. else {
  96176. serializationObject.materials = serializationObject.materials || [];
  96177. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  96178. serializationObject.materials.push(mesh.material.serialize());
  96179. }
  96180. }
  96181. }
  96182. //serialize geometry
  96183. var geometry = mesh._geometry;
  96184. if (geometry) {
  96185. if (!serializationObject.geometries) {
  96186. serializationObject.geometries = {};
  96187. serializationObject.geometries.boxes = [];
  96188. serializationObject.geometries.spheres = [];
  96189. serializationObject.geometries.cylinders = [];
  96190. serializationObject.geometries.toruses = [];
  96191. serializationObject.geometries.grounds = [];
  96192. serializationObject.geometries.planes = [];
  96193. serializationObject.geometries.torusKnots = [];
  96194. serializationObject.geometries.vertexData = [];
  96195. }
  96196. serializeGeometry(geometry, serializationObject.geometries);
  96197. }
  96198. // Skeletons
  96199. if (mesh.skeleton) {
  96200. serializationObject.skeletons = serializationObject.skeletons || [];
  96201. serializationObject.skeletons.push(mesh.skeleton.serialize());
  96202. }
  96203. //serialize the actual mesh
  96204. serializationObject.meshes = serializationObject.meshes || [];
  96205. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96206. }
  96207. };
  96208. var SceneSerializer = /** @class */ (function () {
  96209. function SceneSerializer() {
  96210. }
  96211. SceneSerializer.ClearCache = function () {
  96212. serializedGeometries = [];
  96213. };
  96214. SceneSerializer.Serialize = function (scene) {
  96215. var serializationObject = {};
  96216. SceneSerializer.ClearCache();
  96217. // Scene
  96218. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  96219. serializationObject.autoClear = scene.autoClear;
  96220. serializationObject.clearColor = scene.clearColor.asArray();
  96221. serializationObject.ambientColor = scene.ambientColor.asArray();
  96222. serializationObject.gravity = scene.gravity.asArray();
  96223. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  96224. serializationObject.workerCollisions = scene.workerCollisions;
  96225. // Fog
  96226. if (scene.fogMode && scene.fogMode !== 0) {
  96227. serializationObject.fogMode = scene.fogMode;
  96228. serializationObject.fogColor = scene.fogColor.asArray();
  96229. serializationObject.fogStart = scene.fogStart;
  96230. serializationObject.fogEnd = scene.fogEnd;
  96231. serializationObject.fogDensity = scene.fogDensity;
  96232. }
  96233. //Physics
  96234. if (scene.isPhysicsEnabled()) {
  96235. var physicEngine = scene.getPhysicsEngine();
  96236. if (physicEngine) {
  96237. serializationObject.physicsEnabled = true;
  96238. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  96239. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  96240. }
  96241. }
  96242. // Metadata
  96243. if (scene.metadata) {
  96244. serializationObject.metadata = scene.metadata;
  96245. }
  96246. // Morph targets
  96247. serializationObject.morphTargetManagers = [];
  96248. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  96249. var abstractMesh = _a[_i];
  96250. var manager = abstractMesh.morphTargetManager;
  96251. if (manager) {
  96252. serializationObject.morphTargetManagers.push(manager.serialize());
  96253. }
  96254. }
  96255. // Lights
  96256. serializationObject.lights = [];
  96257. var index;
  96258. var light;
  96259. for (index = 0; index < scene.lights.length; index++) {
  96260. light = scene.lights[index];
  96261. if (!light.doNotSerialize) {
  96262. serializationObject.lights.push(light.serialize());
  96263. }
  96264. }
  96265. // Cameras
  96266. serializationObject.cameras = [];
  96267. for (index = 0; index < scene.cameras.length; index++) {
  96268. var camera = scene.cameras[index];
  96269. if (!camera.doNotSerialize) {
  96270. serializationObject.cameras.push(camera.serialize());
  96271. }
  96272. }
  96273. if (scene.activeCamera) {
  96274. serializationObject.activeCameraID = scene.activeCamera.id;
  96275. }
  96276. // Animations
  96277. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  96278. // Materials
  96279. serializationObject.materials = [];
  96280. serializationObject.multiMaterials = [];
  96281. var material;
  96282. for (index = 0; index < scene.materials.length; index++) {
  96283. material = scene.materials[index];
  96284. if (!material.doNotSerialize) {
  96285. serializationObject.materials.push(material.serialize());
  96286. }
  96287. }
  96288. // MultiMaterials
  96289. serializationObject.multiMaterials = [];
  96290. for (index = 0; index < scene.multiMaterials.length; index++) {
  96291. var multiMaterial = scene.multiMaterials[index];
  96292. serializationObject.multiMaterials.push(multiMaterial.serialize());
  96293. }
  96294. // Environment texture
  96295. if (scene.environmentTexture) {
  96296. serializationObject.environmentTexture = scene.environmentTexture.name;
  96297. }
  96298. // Skeletons
  96299. serializationObject.skeletons = [];
  96300. for (index = 0; index < scene.skeletons.length; index++) {
  96301. var skeleton = scene.skeletons[index];
  96302. if (!skeleton.doNotSerialize) {
  96303. serializationObject.skeletons.push(skeleton.serialize());
  96304. }
  96305. }
  96306. // Transform nodes
  96307. serializationObject.transformNodes = [];
  96308. for (index = 0; index < scene.transformNodes.length; index++) {
  96309. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  96310. }
  96311. // Geometries
  96312. serializationObject.geometries = {};
  96313. serializationObject.geometries.boxes = [];
  96314. serializationObject.geometries.spheres = [];
  96315. serializationObject.geometries.cylinders = [];
  96316. serializationObject.geometries.toruses = [];
  96317. serializationObject.geometries.grounds = [];
  96318. serializationObject.geometries.planes = [];
  96319. serializationObject.geometries.torusKnots = [];
  96320. serializationObject.geometries.vertexData = [];
  96321. serializedGeometries = [];
  96322. var geometries = scene.getGeometries();
  96323. for (index = 0; index < geometries.length; index++) {
  96324. var geometry = geometries[index];
  96325. if (geometry.isReady()) {
  96326. serializeGeometry(geometry, serializationObject.geometries);
  96327. }
  96328. }
  96329. // Meshes
  96330. serializationObject.meshes = [];
  96331. for (index = 0; index < scene.meshes.length; index++) {
  96332. var abstractMesh = scene.meshes[index];
  96333. if (abstractMesh instanceof BABYLON.Mesh) {
  96334. var mesh = abstractMesh;
  96335. if (!mesh.doNotSerialize) {
  96336. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96337. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96338. }
  96339. }
  96340. }
  96341. }
  96342. // Particles Systems
  96343. serializationObject.particleSystems = [];
  96344. for (index = 0; index < scene.particleSystems.length; index++) {
  96345. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  96346. }
  96347. // Lens flares
  96348. serializationObject.lensFlareSystems = [];
  96349. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  96350. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  96351. }
  96352. // Shadows
  96353. serializationObject.shadowGenerators = [];
  96354. for (index = 0; index < scene.lights.length; index++) {
  96355. light = scene.lights[index];
  96356. var shadowGenerator = light.getShadowGenerator();
  96357. if (shadowGenerator) {
  96358. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  96359. }
  96360. }
  96361. // Action Manager
  96362. if (scene.actionManager) {
  96363. serializationObject.actions = scene.actionManager.serialize("scene");
  96364. }
  96365. // Audio
  96366. serializationObject.sounds = [];
  96367. for (index = 0; index < scene.soundTracks.length; index++) {
  96368. var soundtrack = scene.soundTracks[index];
  96369. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  96370. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  96371. }
  96372. }
  96373. // Effect layers
  96374. serializationObject.effectLayers = [];
  96375. for (index = 0; index < scene.effectLayers.length; index++) {
  96376. var layer = scene.effectLayers[index];
  96377. if (layer.serialize) {
  96378. serializationObject.effectLayers.push(layer.serialize());
  96379. }
  96380. }
  96381. return serializationObject;
  96382. };
  96383. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  96384. if (withParents === void 0) { withParents = false; }
  96385. if (withChildren === void 0) { withChildren = false; }
  96386. var serializationObject = {};
  96387. SceneSerializer.ClearCache();
  96388. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  96389. if (withParents || withChildren) {
  96390. //deliberate for loop! not for each, appended should be processed as well.
  96391. for (var i = 0; i < toSerialize.length; ++i) {
  96392. if (withChildren) {
  96393. toSerialize[i].getDescendants().forEach(function (node) {
  96394. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  96395. toSerialize.push(node);
  96396. }
  96397. });
  96398. }
  96399. //make sure the array doesn't contain the object already
  96400. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  96401. toSerialize.push(toSerialize[i].parent);
  96402. }
  96403. }
  96404. }
  96405. toSerialize.forEach(function (mesh) {
  96406. finalizeSingleMesh(mesh, serializationObject);
  96407. });
  96408. return serializationObject;
  96409. };
  96410. return SceneSerializer;
  96411. }());
  96412. BABYLON.SceneSerializer = SceneSerializer;
  96413. })(BABYLON || (BABYLON = {}));
  96414. //# sourceMappingURL=babylon.sceneSerializer.js.map
  96415. var BABYLON;
  96416. (function (BABYLON) {
  96417. var ReflectionProbe = /** @class */ (function () {
  96418. function ReflectionProbe(name, size, scene, generateMipMaps) {
  96419. if (generateMipMaps === void 0) { generateMipMaps = true; }
  96420. var _this = this;
  96421. this.name = name;
  96422. this._viewMatrix = BABYLON.Matrix.Identity();
  96423. this._target = BABYLON.Vector3.Zero();
  96424. this._add = BABYLON.Vector3.Zero();
  96425. this._invertYAxis = false;
  96426. this.position = BABYLON.Vector3.Zero();
  96427. this._scene = scene;
  96428. this._scene.reflectionProbes.push(this);
  96429. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  96430. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  96431. switch (faceIndex) {
  96432. case 0:
  96433. _this._add.copyFromFloats(1, 0, 0);
  96434. break;
  96435. case 1:
  96436. _this._add.copyFromFloats(-1, 0, 0);
  96437. break;
  96438. case 2:
  96439. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  96440. break;
  96441. case 3:
  96442. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  96443. break;
  96444. case 4:
  96445. _this._add.copyFromFloats(0, 0, 1);
  96446. break;
  96447. case 5:
  96448. _this._add.copyFromFloats(0, 0, -1);
  96449. break;
  96450. }
  96451. if (_this._attachedMesh) {
  96452. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  96453. }
  96454. _this.position.addToRef(_this._add, _this._target);
  96455. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  96456. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  96457. scene._forcedViewPosition = _this.position;
  96458. });
  96459. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  96460. scene._forcedViewPosition = null;
  96461. scene.updateTransformMatrix(true);
  96462. });
  96463. if (scene.activeCamera) {
  96464. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  96465. }
  96466. }
  96467. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  96468. get: function () {
  96469. return this._renderTargetTexture.samples;
  96470. },
  96471. set: function (value) {
  96472. this._renderTargetTexture.samples = value;
  96473. },
  96474. enumerable: true,
  96475. configurable: true
  96476. });
  96477. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  96478. get: function () {
  96479. return this._renderTargetTexture.refreshRate;
  96480. },
  96481. set: function (value) {
  96482. this._renderTargetTexture.refreshRate = value;
  96483. },
  96484. enumerable: true,
  96485. configurable: true
  96486. });
  96487. ReflectionProbe.prototype.getScene = function () {
  96488. return this._scene;
  96489. };
  96490. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  96491. get: function () {
  96492. return this._renderTargetTexture;
  96493. },
  96494. enumerable: true,
  96495. configurable: true
  96496. });
  96497. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  96498. get: function () {
  96499. return this._renderTargetTexture.renderList;
  96500. },
  96501. enumerable: true,
  96502. configurable: true
  96503. });
  96504. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  96505. this._attachedMesh = mesh;
  96506. };
  96507. /**
  96508. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  96509. *
  96510. * @param renderingGroupId The rendering group id corresponding to its index
  96511. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  96512. */
  96513. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  96514. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  96515. };
  96516. ReflectionProbe.prototype.dispose = function () {
  96517. var index = this._scene.reflectionProbes.indexOf(this);
  96518. if (index !== -1) {
  96519. // Remove from the scene if found
  96520. this._scene.reflectionProbes.splice(index, 1);
  96521. }
  96522. if (this._renderTargetTexture) {
  96523. this._renderTargetTexture.dispose();
  96524. this._renderTargetTexture = null;
  96525. }
  96526. };
  96527. return ReflectionProbe;
  96528. }());
  96529. BABYLON.ReflectionProbe = ReflectionProbe;
  96530. })(BABYLON || (BABYLON = {}));
  96531. //# sourceMappingURL=babylon.reflectionProbe.js.map
  96532. var BABYLON;
  96533. (function (BABYLON) {
  96534. var Layer = /** @class */ (function () {
  96535. function Layer(name, imgUrl, scene, isBackground, color) {
  96536. this.name = name;
  96537. this.scale = new BABYLON.Vector2(1, 1);
  96538. this.offset = new BABYLON.Vector2(0, 0);
  96539. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  96540. this.layerMask = 0x0FFFFFFF;
  96541. this._vertexBuffers = {};
  96542. // Events
  96543. /**
  96544. * An event triggered when the layer is disposed.
  96545. */
  96546. this.onDisposeObservable = new BABYLON.Observable();
  96547. /**
  96548. * An event triggered before rendering the scene
  96549. */
  96550. this.onBeforeRenderObservable = new BABYLON.Observable();
  96551. /**
  96552. * An event triggered after rendering the scene
  96553. */
  96554. this.onAfterRenderObservable = new BABYLON.Observable();
  96555. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  96556. this.isBackground = isBackground === undefined ? true : isBackground;
  96557. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  96558. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  96559. this._scene.layers.push(this);
  96560. var engine = this._scene.getEngine();
  96561. // VBO
  96562. var vertices = [];
  96563. vertices.push(1, 1);
  96564. vertices.push(-1, 1);
  96565. vertices.push(-1, -1);
  96566. vertices.push(1, -1);
  96567. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96568. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96569. this._createIndexBuffer();
  96570. // Effects
  96571. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  96572. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  96573. }
  96574. Object.defineProperty(Layer.prototype, "onDispose", {
  96575. set: function (callback) {
  96576. if (this._onDisposeObserver) {
  96577. this.onDisposeObservable.remove(this._onDisposeObserver);
  96578. }
  96579. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96580. },
  96581. enumerable: true,
  96582. configurable: true
  96583. });
  96584. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  96585. set: function (callback) {
  96586. if (this._onBeforeRenderObserver) {
  96587. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  96588. }
  96589. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  96590. },
  96591. enumerable: true,
  96592. configurable: true
  96593. });
  96594. Object.defineProperty(Layer.prototype, "onAfterRender", {
  96595. set: function (callback) {
  96596. if (this._onAfterRenderObserver) {
  96597. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96598. }
  96599. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  96600. },
  96601. enumerable: true,
  96602. configurable: true
  96603. });
  96604. Layer.prototype._createIndexBuffer = function () {
  96605. var engine = this._scene.getEngine();
  96606. // Indices
  96607. var indices = [];
  96608. indices.push(0);
  96609. indices.push(1);
  96610. indices.push(2);
  96611. indices.push(0);
  96612. indices.push(2);
  96613. indices.push(3);
  96614. this._indexBuffer = engine.createIndexBuffer(indices);
  96615. };
  96616. Layer.prototype._rebuild = function () {
  96617. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96618. if (vb) {
  96619. vb._rebuild();
  96620. }
  96621. this._createIndexBuffer();
  96622. };
  96623. Layer.prototype.render = function () {
  96624. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  96625. // Check
  96626. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  96627. return;
  96628. var engine = this._scene.getEngine();
  96629. this.onBeforeRenderObservable.notifyObservers(this);
  96630. // Render
  96631. engine.enableEffect(currentEffect);
  96632. engine.setState(false);
  96633. // Texture
  96634. currentEffect.setTexture("textureSampler", this.texture);
  96635. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  96636. // Color
  96637. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  96638. // Scale / offset
  96639. currentEffect.setVector2("offset", this.offset);
  96640. currentEffect.setVector2("scale", this.scale);
  96641. // VBOs
  96642. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96643. // Draw order
  96644. if (!this.alphaTest) {
  96645. engine.setAlphaMode(this.alphaBlendingMode);
  96646. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96647. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96648. }
  96649. else {
  96650. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96651. }
  96652. this.onAfterRenderObservable.notifyObservers(this);
  96653. };
  96654. Layer.prototype.dispose = function () {
  96655. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96656. if (vertexBuffer) {
  96657. vertexBuffer.dispose();
  96658. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96659. }
  96660. if (this._indexBuffer) {
  96661. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96662. this._indexBuffer = null;
  96663. }
  96664. if (this.texture) {
  96665. this.texture.dispose();
  96666. this.texture = null;
  96667. }
  96668. // Remove from scene
  96669. var index = this._scene.layers.indexOf(this);
  96670. this._scene.layers.splice(index, 1);
  96671. // Callback
  96672. this.onDisposeObservable.notifyObservers(this);
  96673. this.onDisposeObservable.clear();
  96674. this.onAfterRenderObservable.clear();
  96675. this.onBeforeRenderObservable.clear();
  96676. };
  96677. return Layer;
  96678. }());
  96679. BABYLON.Layer = Layer;
  96680. })(BABYLON || (BABYLON = {}));
  96681. //# sourceMappingURL=babylon.layer.js.map
  96682. var BABYLON;
  96683. (function (BABYLON) {
  96684. var TextureTools = /** @class */ (function () {
  96685. function TextureTools() {
  96686. }
  96687. /**
  96688. * Uses the GPU to create a copy texture rescaled at a given size
  96689. * @param texture Texture to copy from
  96690. * @param width Desired width
  96691. * @param height Desired height
  96692. * @return Generated texture
  96693. */
  96694. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  96695. if (useBilinearMode === void 0) { useBilinearMode = true; }
  96696. var scene = texture.getScene();
  96697. var engine = scene.getEngine();
  96698. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  96699. rtt.wrapU = texture.wrapU;
  96700. rtt.wrapV = texture.wrapV;
  96701. rtt.uOffset = texture.uOffset;
  96702. rtt.vOffset = texture.vOffset;
  96703. rtt.uScale = texture.uScale;
  96704. rtt.vScale = texture.vScale;
  96705. rtt.uAng = texture.uAng;
  96706. rtt.vAng = texture.vAng;
  96707. rtt.wAng = texture.wAng;
  96708. rtt.coordinatesIndex = texture.coordinatesIndex;
  96709. rtt.level = texture.level;
  96710. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  96711. rtt._texture.isReady = false;
  96712. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96713. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96714. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96715. passPostProcess.getEffect().executeWhenCompiled(function () {
  96716. passPostProcess.onApply = function (effect) {
  96717. effect.setTexture("textureSampler", texture);
  96718. };
  96719. var internalTexture = rtt.getInternalTexture();
  96720. if (internalTexture) {
  96721. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  96722. engine.unBindFramebuffer(internalTexture);
  96723. rtt.disposeFramebufferObjects();
  96724. passPostProcess.dispose();
  96725. internalTexture.isReady = true;
  96726. }
  96727. });
  96728. return rtt;
  96729. };
  96730. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  96731. if (!scene._environmentBRDFTexture) {
  96732. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96733. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96734. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96735. scene._environmentBRDFTexture = texture;
  96736. }
  96737. return scene._environmentBRDFTexture;
  96738. };
  96739. 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=";
  96740. return TextureTools;
  96741. }());
  96742. BABYLON.TextureTools = TextureTools;
  96743. })(BABYLON || (BABYLON = {}));
  96744. //# sourceMappingURL=babylon.textureTools.js.map
  96745. var BABYLON;
  96746. (function (BABYLON) {
  96747. var FramingBehavior = /** @class */ (function () {
  96748. function FramingBehavior() {
  96749. this._mode = FramingBehavior.FitFrustumSidesMode;
  96750. this._radiusScale = 1.0;
  96751. this._positionScale = 0.5;
  96752. this._defaultElevation = 0.3;
  96753. this._elevationReturnTime = 1500;
  96754. this._elevationReturnWaitTime = 1000;
  96755. this._zoomStopsAnimation = false;
  96756. this._framingTime = 1500;
  96757. this._isPointerDown = false;
  96758. this._lastInteractionTime = -Infinity;
  96759. // Framing control
  96760. this._animatables = new Array();
  96761. this._betaIsAnimating = false;
  96762. }
  96763. Object.defineProperty(FramingBehavior.prototype, "name", {
  96764. get: function () {
  96765. return "Framing";
  96766. },
  96767. enumerable: true,
  96768. configurable: true
  96769. });
  96770. Object.defineProperty(FramingBehavior.prototype, "mode", {
  96771. /**
  96772. * Gets current mode used by the behavior.
  96773. */
  96774. get: function () {
  96775. return this._mode;
  96776. },
  96777. /**
  96778. * Sets the current mode used by the behavior
  96779. */
  96780. set: function (mode) {
  96781. this._mode = mode;
  96782. },
  96783. enumerable: true,
  96784. configurable: true
  96785. });
  96786. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  96787. /**
  96788. * Gets the scale applied to the radius
  96789. */
  96790. get: function () {
  96791. return this._radiusScale;
  96792. },
  96793. /**
  96794. * Sets the scale applied to the radius (1 by default)
  96795. */
  96796. set: function (radius) {
  96797. this._radiusScale = radius;
  96798. },
  96799. enumerable: true,
  96800. configurable: true
  96801. });
  96802. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  96803. /**
  96804. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96805. */
  96806. get: function () {
  96807. return this._positionScale;
  96808. },
  96809. /**
  96810. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96811. */
  96812. set: function (scale) {
  96813. this._positionScale = scale;
  96814. },
  96815. enumerable: true,
  96816. configurable: true
  96817. });
  96818. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  96819. /**
  96820. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96821. * behaviour is triggered, in radians.
  96822. */
  96823. get: function () {
  96824. return this._defaultElevation;
  96825. },
  96826. /**
  96827. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96828. * behaviour is triggered, in radians.
  96829. */
  96830. set: function (elevation) {
  96831. this._defaultElevation = elevation;
  96832. },
  96833. enumerable: true,
  96834. configurable: true
  96835. });
  96836. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  96837. /**
  96838. * Gets the time (in milliseconds) taken to return to the default beta position.
  96839. * Negative value indicates camera should not return to default.
  96840. */
  96841. get: function () {
  96842. return this._elevationReturnTime;
  96843. },
  96844. /**
  96845. * Sets the time (in milliseconds) taken to return to the default beta position.
  96846. * Negative value indicates camera should not return to default.
  96847. */
  96848. set: function (speed) {
  96849. this._elevationReturnTime = speed;
  96850. },
  96851. enumerable: true,
  96852. configurable: true
  96853. });
  96854. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  96855. /**
  96856. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96857. */
  96858. get: function () {
  96859. return this._elevationReturnWaitTime;
  96860. },
  96861. /**
  96862. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96863. */
  96864. set: function (time) {
  96865. this._elevationReturnWaitTime = time;
  96866. },
  96867. enumerable: true,
  96868. configurable: true
  96869. });
  96870. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  96871. /**
  96872. * Gets the flag that indicates if user zooming should stop animation.
  96873. */
  96874. get: function () {
  96875. return this._zoomStopsAnimation;
  96876. },
  96877. /**
  96878. * Sets the flag that indicates if user zooming should stop animation.
  96879. */
  96880. set: function (flag) {
  96881. this._zoomStopsAnimation = flag;
  96882. },
  96883. enumerable: true,
  96884. configurable: true
  96885. });
  96886. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  96887. /**
  96888. * Gets the transition time when framing the mesh, in milliseconds
  96889. */
  96890. get: function () {
  96891. return this._framingTime;
  96892. },
  96893. /**
  96894. * Sets the transition time when framing the mesh, in milliseconds
  96895. */
  96896. set: function (time) {
  96897. this._framingTime = time;
  96898. },
  96899. enumerable: true,
  96900. configurable: true
  96901. });
  96902. FramingBehavior.prototype.init = function () {
  96903. // Do notihng
  96904. };
  96905. FramingBehavior.prototype.attach = function (camera) {
  96906. var _this = this;
  96907. this._attachedCamera = camera;
  96908. var scene = this._attachedCamera.getScene();
  96909. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  96910. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  96911. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96912. _this._isPointerDown = true;
  96913. return;
  96914. }
  96915. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  96916. _this._isPointerDown = false;
  96917. }
  96918. });
  96919. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96920. if (mesh) {
  96921. _this.zoomOnMesh(mesh);
  96922. }
  96923. });
  96924. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96925. // Stop the animation if there is user interaction and the animation should stop for this interaction
  96926. _this._applyUserInteraction();
  96927. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  96928. // back to the default position after a given timeout
  96929. _this._maintainCameraAboveGround();
  96930. });
  96931. };
  96932. FramingBehavior.prototype.detach = function () {
  96933. if (!this._attachedCamera) {
  96934. return;
  96935. }
  96936. var scene = this._attachedCamera.getScene();
  96937. if (this._onPrePointerObservableObserver) {
  96938. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  96939. }
  96940. if (this._onAfterCheckInputsObserver) {
  96941. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96942. }
  96943. if (this._onMeshTargetChangedObserver) {
  96944. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96945. }
  96946. this._attachedCamera = null;
  96947. };
  96948. /**
  96949. * Targets the given mesh and updates zoom level accordingly.
  96950. * @param mesh The mesh to target.
  96951. * @param radius Optional. If a cached radius position already exists, overrides default.
  96952. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96953. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96954. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96955. */
  96956. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96957. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96958. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96959. mesh.computeWorldMatrix(true);
  96960. var boundingBox = mesh.getBoundingInfo().boundingBox;
  96961. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  96962. };
  96963. /**
  96964. * Targets the given mesh with its children and updates zoom level accordingly.
  96965. * @param mesh The mesh to target.
  96966. * @param radius Optional. If a cached radius position already exists, overrides default.
  96967. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96968. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96969. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96970. */
  96971. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96972. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96973. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96974. mesh.computeWorldMatrix(true);
  96975. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  96976. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  96977. };
  96978. /**
  96979. * Targets the given meshes with their children and updates zoom level accordingly.
  96980. * @param meshes The mesh to target.
  96981. * @param radius Optional. If a cached radius position already exists, overrides default.
  96982. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96983. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96984. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96985. */
  96986. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  96987. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96988. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96989. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  96990. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  96991. for (var i = 0; i < meshes.length; i++) {
  96992. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  96993. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  96994. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  96995. }
  96996. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  96997. };
  96998. /**
  96999. * Targets the given mesh and updates zoom level accordingly.
  97000. * @param mesh The mesh to target.
  97001. * @param radius Optional. If a cached radius position already exists, overrides default.
  97002. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97003. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97004. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97005. */
  97006. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  97007. var _this = this;
  97008. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97009. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97010. var zoomTarget;
  97011. if (!this._attachedCamera) {
  97012. return;
  97013. }
  97014. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  97015. var bottom = minimumWorld.y;
  97016. var top = maximumWorld.y;
  97017. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  97018. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  97019. if (focusOnOriginXZ) {
  97020. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  97021. }
  97022. else {
  97023. var centerWorld = minimumWorld.add(radiusWorld);
  97024. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  97025. }
  97026. if (!this._vectorTransition) {
  97027. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  97028. }
  97029. this._betaIsAnimating = true;
  97030. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  97031. if (animatable) {
  97032. this._animatables.push(animatable);
  97033. }
  97034. // sets the radius and lower radius bounds
  97035. // Small delta ensures camera is not always at lower zoom limit.
  97036. var radius = 0;
  97037. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  97038. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97039. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  97040. radius = position;
  97041. }
  97042. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97043. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97044. if (this._attachedCamera.lowerRadiusLimit === null) {
  97045. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  97046. }
  97047. }
  97048. // Set sensibilities
  97049. var extend = maximumWorld.subtract(minimumWorld).length();
  97050. this._attachedCamera.panningSensibility = 5000 / extend;
  97051. this._attachedCamera.wheelPrecision = 100 / radius;
  97052. // transition to new radius
  97053. if (!this._radiusTransition) {
  97054. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97055. }
  97056. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  97057. _this.stopAllAnimations();
  97058. if (onAnimationEnd) {
  97059. onAnimationEnd();
  97060. }
  97061. if (_this._attachedCamera) {
  97062. _this._attachedCamera.storeState();
  97063. }
  97064. });
  97065. if (animatable) {
  97066. this._animatables.push(animatable);
  97067. }
  97068. };
  97069. /**
  97070. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  97071. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  97072. * frustum width.
  97073. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  97074. * to fully enclose the mesh in the viewing frustum.
  97075. */
  97076. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  97077. var size = maximumWorld.subtract(minimumWorld);
  97078. var boxVectorGlobalDiagonal = size.length();
  97079. var frustumSlope = this._getFrustumSlope();
  97080. // Formula for setting distance
  97081. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  97082. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  97083. // Horizon distance
  97084. var radius = radiusWithoutFraming * this._radiusScale;
  97085. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  97086. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  97087. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  97088. var camera = this._attachedCamera;
  97089. if (!camera) {
  97090. return 0;
  97091. }
  97092. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97093. // Don't exceed the requested limit
  97094. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  97095. }
  97096. // Don't exceed the upper radius limit
  97097. if (camera.upperRadiusLimit) {
  97098. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  97099. }
  97100. return distance;
  97101. };
  97102. /**
  97103. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  97104. * is automatically returned to its default position (expected to be above ground plane).
  97105. */
  97106. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  97107. var _this = this;
  97108. if (this._elevationReturnTime < 0) {
  97109. return;
  97110. }
  97111. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  97112. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  97113. var limitBeta = Math.PI * 0.5;
  97114. // Bring the camera back up if below the ground plane
  97115. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  97116. this._betaIsAnimating = true;
  97117. //Transition to new position
  97118. this.stopAllAnimations();
  97119. if (!this._betaTransition) {
  97120. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97121. }
  97122. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  97123. _this._clearAnimationLocks();
  97124. _this.stopAllAnimations();
  97125. });
  97126. if (animatabe) {
  97127. this._animatables.push(animatabe);
  97128. }
  97129. }
  97130. };
  97131. /**
  97132. * Returns the frustum slope based on the canvas ratio and camera FOV
  97133. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  97134. */
  97135. FramingBehavior.prototype._getFrustumSlope = function () {
  97136. // Calculate the viewport ratio
  97137. // Aspect Ratio is Height/Width.
  97138. var camera = this._attachedCamera;
  97139. if (!camera) {
  97140. return BABYLON.Vector2.Zero();
  97141. }
  97142. var engine = camera.getScene().getEngine();
  97143. var aspectRatio = engine.getAspectRatio(camera);
  97144. // Camera FOV is the vertical field of view (top-bottom) in radians.
  97145. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  97146. var frustumSlopeY = Math.tan(camera.fov / 2);
  97147. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  97148. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  97149. // along the forward vector.
  97150. var frustumSlopeX = frustumSlopeY * aspectRatio;
  97151. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  97152. };
  97153. /**
  97154. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  97155. */
  97156. FramingBehavior.prototype._clearAnimationLocks = function () {
  97157. this._betaIsAnimating = false;
  97158. };
  97159. /**
  97160. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97161. */
  97162. FramingBehavior.prototype._applyUserInteraction = function () {
  97163. if (this.isUserIsMoving) {
  97164. this._lastInteractionTime = BABYLON.Tools.Now;
  97165. this.stopAllAnimations();
  97166. this._clearAnimationLocks();
  97167. }
  97168. };
  97169. /**
  97170. * Stops and removes all animations that have been applied to the camera
  97171. */
  97172. FramingBehavior.prototype.stopAllAnimations = function () {
  97173. if (this._attachedCamera) {
  97174. this._attachedCamera.animations = [];
  97175. }
  97176. while (this._animatables.length) {
  97177. if (this._animatables[0]) {
  97178. this._animatables[0].onAnimationEnd = null;
  97179. this._animatables[0].stop();
  97180. }
  97181. this._animatables.shift();
  97182. }
  97183. };
  97184. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  97185. /**
  97186. * Gets a value indicating if the user is moving the camera
  97187. */
  97188. get: function () {
  97189. if (!this._attachedCamera) {
  97190. return false;
  97191. }
  97192. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97193. this._attachedCamera.inertialBetaOffset !== 0 ||
  97194. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97195. this._attachedCamera.inertialPanningX !== 0 ||
  97196. this._attachedCamera.inertialPanningY !== 0 ||
  97197. this._isPointerDown;
  97198. },
  97199. enumerable: true,
  97200. configurable: true
  97201. });
  97202. /**
  97203. * The easing function used by animations
  97204. */
  97205. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  97206. /**
  97207. * The easing mode used by animations
  97208. */
  97209. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  97210. // Statics
  97211. /**
  97212. * The camera can move all the way towards the mesh.
  97213. */
  97214. FramingBehavior.IgnoreBoundsSizeMode = 0;
  97215. /**
  97216. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  97217. */
  97218. FramingBehavior.FitFrustumSidesMode = 1;
  97219. return FramingBehavior;
  97220. }());
  97221. BABYLON.FramingBehavior = FramingBehavior;
  97222. })(BABYLON || (BABYLON = {}));
  97223. //# sourceMappingURL=babylon.framingBehavior.js.map
  97224. var BABYLON;
  97225. (function (BABYLON) {
  97226. /**
  97227. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  97228. */
  97229. var BouncingBehavior = /** @class */ (function () {
  97230. function BouncingBehavior() {
  97231. /**
  97232. * The duration of the animation, in milliseconds
  97233. */
  97234. this.transitionDuration = 450;
  97235. /**
  97236. * Length of the distance animated by the transition when lower radius is reached
  97237. */
  97238. this.lowerRadiusTransitionRange = 2;
  97239. /**
  97240. * Length of the distance animated by the transition when upper radius is reached
  97241. */
  97242. this.upperRadiusTransitionRange = -2;
  97243. this._autoTransitionRange = false;
  97244. // Animations
  97245. this._radiusIsAnimating = false;
  97246. this._radiusBounceTransition = null;
  97247. this._animatables = new Array();
  97248. }
  97249. Object.defineProperty(BouncingBehavior.prototype, "name", {
  97250. get: function () {
  97251. return "Bouncing";
  97252. },
  97253. enumerable: true,
  97254. configurable: true
  97255. });
  97256. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  97257. /**
  97258. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97259. */
  97260. get: function () {
  97261. return this._autoTransitionRange;
  97262. },
  97263. /**
  97264. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97265. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  97266. */
  97267. set: function (value) {
  97268. var _this = this;
  97269. if (this._autoTransitionRange === value) {
  97270. return;
  97271. }
  97272. this._autoTransitionRange = value;
  97273. var camera = this._attachedCamera;
  97274. if (!camera) {
  97275. return;
  97276. }
  97277. if (value) {
  97278. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  97279. if (!mesh) {
  97280. return;
  97281. }
  97282. mesh.computeWorldMatrix(true);
  97283. var diagonal = mesh.getBoundingInfo().diagonalLength;
  97284. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  97285. _this.upperRadiusTransitionRange = diagonal * 0.05;
  97286. });
  97287. }
  97288. else if (this._onMeshTargetChangedObserver) {
  97289. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97290. }
  97291. },
  97292. enumerable: true,
  97293. configurable: true
  97294. });
  97295. BouncingBehavior.prototype.init = function () {
  97296. // Do notihng
  97297. };
  97298. BouncingBehavior.prototype.attach = function (camera) {
  97299. var _this = this;
  97300. this._attachedCamera = camera;
  97301. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97302. if (!_this._attachedCamera) {
  97303. return;
  97304. }
  97305. // Add the bounce animation to the lower radius limit
  97306. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  97307. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  97308. }
  97309. // Add the bounce animation to the upper radius limit
  97310. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  97311. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  97312. }
  97313. });
  97314. };
  97315. BouncingBehavior.prototype.detach = function () {
  97316. if (!this._attachedCamera) {
  97317. return;
  97318. }
  97319. if (this._onAfterCheckInputsObserver) {
  97320. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97321. }
  97322. if (this._onMeshTargetChangedObserver) {
  97323. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97324. }
  97325. this._attachedCamera = null;
  97326. };
  97327. /**
  97328. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  97329. * @param radiusLimit The limit to check against.
  97330. * @return Bool to indicate if at limit.
  97331. */
  97332. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  97333. if (!this._attachedCamera) {
  97334. return false;
  97335. }
  97336. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  97337. return true;
  97338. }
  97339. return false;
  97340. };
  97341. /**
  97342. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  97343. * @param radiusDelta The delta by which to animate to. Can be negative.
  97344. */
  97345. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  97346. var _this = this;
  97347. if (!this._attachedCamera) {
  97348. return;
  97349. }
  97350. if (!this._radiusBounceTransition) {
  97351. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  97352. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  97353. }
  97354. // Prevent zoom until bounce has completed
  97355. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  97356. this._attachedCamera.wheelPrecision = Infinity;
  97357. this._attachedCamera.inertialRadiusOffset = 0;
  97358. // Animate to the radius limit
  97359. this.stopAllAnimations();
  97360. this._radiusIsAnimating = true;
  97361. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  97362. if (animatable) {
  97363. this._animatables.push(animatable);
  97364. }
  97365. };
  97366. /**
  97367. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  97368. */
  97369. BouncingBehavior.prototype._clearAnimationLocks = function () {
  97370. this._radiusIsAnimating = false;
  97371. if (this._attachedCamera) {
  97372. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  97373. }
  97374. };
  97375. /**
  97376. * Stops and removes all animations that have been applied to the camera
  97377. */
  97378. BouncingBehavior.prototype.stopAllAnimations = function () {
  97379. if (this._attachedCamera) {
  97380. this._attachedCamera.animations = [];
  97381. }
  97382. while (this._animatables.length) {
  97383. this._animatables[0].onAnimationEnd = null;
  97384. this._animatables[0].stop();
  97385. this._animatables.shift();
  97386. }
  97387. };
  97388. /**
  97389. * The easing function used by animations
  97390. */
  97391. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  97392. /**
  97393. * The easing mode used by animations
  97394. */
  97395. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  97396. return BouncingBehavior;
  97397. }());
  97398. BABYLON.BouncingBehavior = BouncingBehavior;
  97399. })(BABYLON || (BABYLON = {}));
  97400. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  97401. var BABYLON;
  97402. (function (BABYLON) {
  97403. var AutoRotationBehavior = /** @class */ (function () {
  97404. function AutoRotationBehavior() {
  97405. this._zoomStopsAnimation = false;
  97406. this._idleRotationSpeed = 0.05;
  97407. this._idleRotationWaitTime = 2000;
  97408. this._idleRotationSpinupTime = 2000;
  97409. this._isPointerDown = false;
  97410. this._lastFrameTime = null;
  97411. this._lastInteractionTime = -Infinity;
  97412. this._cameraRotationSpeed = 0;
  97413. this._lastFrameRadius = 0;
  97414. }
  97415. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  97416. get: function () {
  97417. return "AutoRotation";
  97418. },
  97419. enumerable: true,
  97420. configurable: true
  97421. });
  97422. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  97423. /**
  97424. * Gets the flag that indicates if user zooming should stop animation.
  97425. */
  97426. get: function () {
  97427. return this._zoomStopsAnimation;
  97428. },
  97429. /**
  97430. * Sets the flag that indicates if user zooming should stop animation.
  97431. */
  97432. set: function (flag) {
  97433. this._zoomStopsAnimation = flag;
  97434. },
  97435. enumerable: true,
  97436. configurable: true
  97437. });
  97438. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  97439. /**
  97440. * Gets the default speed at which the camera rotates around the model.
  97441. */
  97442. get: function () {
  97443. return this._idleRotationSpeed;
  97444. },
  97445. /**
  97446. * Sets the default speed at which the camera rotates around the model.
  97447. */
  97448. set: function (speed) {
  97449. this._idleRotationSpeed = speed;
  97450. },
  97451. enumerable: true,
  97452. configurable: true
  97453. });
  97454. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  97455. /**
  97456. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  97457. */
  97458. get: function () {
  97459. return this._idleRotationWaitTime;
  97460. },
  97461. /**
  97462. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  97463. */
  97464. set: function (time) {
  97465. this._idleRotationWaitTime = time;
  97466. },
  97467. enumerable: true,
  97468. configurable: true
  97469. });
  97470. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  97471. /**
  97472. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97473. */
  97474. get: function () {
  97475. return this._idleRotationSpinupTime;
  97476. },
  97477. /**
  97478. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97479. */
  97480. set: function (time) {
  97481. this._idleRotationSpinupTime = time;
  97482. },
  97483. enumerable: true,
  97484. configurable: true
  97485. });
  97486. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  97487. /**
  97488. * Gets a value indicating if the camera is currently rotating because of this behavior
  97489. */
  97490. get: function () {
  97491. return Math.abs(this._cameraRotationSpeed) > 0;
  97492. },
  97493. enumerable: true,
  97494. configurable: true
  97495. });
  97496. AutoRotationBehavior.prototype.init = function () {
  97497. // Do notihng
  97498. };
  97499. AutoRotationBehavior.prototype.attach = function (camera) {
  97500. var _this = this;
  97501. this._attachedCamera = camera;
  97502. var scene = this._attachedCamera.getScene();
  97503. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97504. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97505. _this._isPointerDown = true;
  97506. return;
  97507. }
  97508. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97509. _this._isPointerDown = false;
  97510. }
  97511. });
  97512. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97513. var now = BABYLON.Tools.Now;
  97514. var dt = 0;
  97515. if (_this._lastFrameTime != null) {
  97516. dt = now - _this._lastFrameTime;
  97517. }
  97518. _this._lastFrameTime = now;
  97519. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97520. _this._applyUserInteraction();
  97521. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  97522. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  97523. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  97524. // Step camera rotation by rotation speed
  97525. if (_this._attachedCamera) {
  97526. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  97527. }
  97528. });
  97529. };
  97530. AutoRotationBehavior.prototype.detach = function () {
  97531. if (!this._attachedCamera) {
  97532. return;
  97533. }
  97534. var scene = this._attachedCamera.getScene();
  97535. if (this._onPrePointerObservableObserver) {
  97536. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97537. }
  97538. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97539. this._attachedCamera = null;
  97540. };
  97541. /**
  97542. * Returns true if user is scrolling.
  97543. * @return true if user is scrolling.
  97544. */
  97545. AutoRotationBehavior.prototype._userIsZooming = function () {
  97546. if (!this._attachedCamera) {
  97547. return false;
  97548. }
  97549. return this._attachedCamera.inertialRadiusOffset !== 0;
  97550. };
  97551. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  97552. if (!this._attachedCamera) {
  97553. return false;
  97554. }
  97555. var zoomHasHitLimit = false;
  97556. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  97557. zoomHasHitLimit = true;
  97558. }
  97559. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  97560. this._lastFrameRadius = this._attachedCamera.radius;
  97561. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  97562. };
  97563. /**
  97564. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97565. */
  97566. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  97567. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  97568. this._lastInteractionTime = BABYLON.Tools.Now;
  97569. }
  97570. };
  97571. // Tools
  97572. AutoRotationBehavior.prototype._userIsMoving = function () {
  97573. if (!this._attachedCamera) {
  97574. return false;
  97575. }
  97576. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97577. this._attachedCamera.inertialBetaOffset !== 0 ||
  97578. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97579. this._attachedCamera.inertialPanningX !== 0 ||
  97580. this._attachedCamera.inertialPanningY !== 0 ||
  97581. this._isPointerDown;
  97582. };
  97583. return AutoRotationBehavior;
  97584. }());
  97585. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  97586. })(BABYLON || (BABYLON = {}));
  97587. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  97588. var BABYLON;
  97589. (function (BABYLON) {
  97590. var NullEngineOptions = /** @class */ (function () {
  97591. function NullEngineOptions() {
  97592. this.renderWidth = 512;
  97593. this.renderHeight = 256;
  97594. this.textureSize = 512;
  97595. this.deterministicLockstep = false;
  97596. this.lockstepMaxSteps = 4;
  97597. }
  97598. return NullEngineOptions;
  97599. }());
  97600. BABYLON.NullEngineOptions = NullEngineOptions;
  97601. /**
  97602. * The null engine class provides support for headless version of babylon.js.
  97603. * This can be used in server side scenario or for testing purposes
  97604. */
  97605. var NullEngine = /** @class */ (function (_super) {
  97606. __extends(NullEngine, _super);
  97607. function NullEngine(options) {
  97608. if (options === void 0) { options = new NullEngineOptions(); }
  97609. var _this = _super.call(this, null) || this;
  97610. if (options.deterministicLockstep === undefined) {
  97611. options.deterministicLockstep = false;
  97612. }
  97613. if (options.lockstepMaxSteps === undefined) {
  97614. options.lockstepMaxSteps = 4;
  97615. }
  97616. _this._options = options;
  97617. // Init caps
  97618. // We consider we are on a webgl1 capable device
  97619. _this._caps = new BABYLON.EngineCapabilities();
  97620. _this._caps.maxTexturesImageUnits = 16;
  97621. _this._caps.maxVertexTextureImageUnits = 16;
  97622. _this._caps.maxTextureSize = 512;
  97623. _this._caps.maxCubemapTextureSize = 512;
  97624. _this._caps.maxRenderTextureSize = 512;
  97625. _this._caps.maxVertexAttribs = 16;
  97626. _this._caps.maxVaryingVectors = 16;
  97627. _this._caps.maxFragmentUniformVectors = 16;
  97628. _this._caps.maxVertexUniformVectors = 16;
  97629. // Extensions
  97630. _this._caps.standardDerivatives = false;
  97631. _this._caps.astc = null;
  97632. _this._caps.s3tc = null;
  97633. _this._caps.pvrtc = null;
  97634. _this._caps.etc1 = null;
  97635. _this._caps.etc2 = null;
  97636. _this._caps.textureAnisotropicFilterExtension = null;
  97637. _this._caps.maxAnisotropy = 0;
  97638. _this._caps.uintIndices = false;
  97639. _this._caps.fragmentDepthSupported = false;
  97640. _this._caps.highPrecisionShaderSupported = true;
  97641. _this._caps.colorBufferFloat = false;
  97642. _this._caps.textureFloat = false;
  97643. _this._caps.textureFloatLinearFiltering = false;
  97644. _this._caps.textureFloatRender = false;
  97645. _this._caps.textureHalfFloat = false;
  97646. _this._caps.textureHalfFloatLinearFiltering = false;
  97647. _this._caps.textureHalfFloatRender = false;
  97648. _this._caps.textureLOD = false;
  97649. _this._caps.drawBuffersExtension = false;
  97650. _this._caps.depthTextureExtension = false;
  97651. _this._caps.vertexArrayObject = false;
  97652. _this._caps.instancedArrays = false;
  97653. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  97654. // Wrappers
  97655. if (typeof URL === "undefined") {
  97656. URL = {
  97657. createObjectURL: function () { },
  97658. revokeObjectURL: function () { }
  97659. };
  97660. }
  97661. if (typeof Blob === "undefined") {
  97662. Blob = function () { };
  97663. }
  97664. return _this;
  97665. }
  97666. NullEngine.prototype.isDeterministicLockStep = function () {
  97667. return this._options.deterministicLockstep;
  97668. };
  97669. NullEngine.prototype.getLockstepMaxSteps = function () {
  97670. return this._options.lockstepMaxSteps;
  97671. };
  97672. NullEngine.prototype.getHardwareScalingLevel = function () {
  97673. return 1.0;
  97674. };
  97675. NullEngine.prototype.createVertexBuffer = function (vertices) {
  97676. return {
  97677. capacity: 0,
  97678. references: 1,
  97679. is32Bits: false
  97680. };
  97681. };
  97682. NullEngine.prototype.createIndexBuffer = function (indices) {
  97683. return {
  97684. capacity: 0,
  97685. references: 1,
  97686. is32Bits: false
  97687. };
  97688. };
  97689. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  97690. if (stencil === void 0) { stencil = false; }
  97691. };
  97692. NullEngine.prototype.getRenderWidth = function (useScreen) {
  97693. if (useScreen === void 0) { useScreen = false; }
  97694. if (!useScreen && this._currentRenderTarget) {
  97695. return this._currentRenderTarget.width;
  97696. }
  97697. return this._options.renderWidth;
  97698. };
  97699. NullEngine.prototype.getRenderHeight = function (useScreen) {
  97700. if (useScreen === void 0) { useScreen = false; }
  97701. if (!useScreen && this._currentRenderTarget) {
  97702. return this._currentRenderTarget.height;
  97703. }
  97704. return this._options.renderHeight;
  97705. };
  97706. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  97707. this._cachedViewport = viewport;
  97708. };
  97709. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  97710. return {
  97711. transformFeedback: null,
  97712. __SPECTOR_rebuildProgram: null
  97713. };
  97714. };
  97715. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  97716. return [];
  97717. };
  97718. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  97719. return [];
  97720. };
  97721. NullEngine.prototype.bindSamplers = function (effect) {
  97722. this._currentEffect = null;
  97723. };
  97724. NullEngine.prototype.enableEffect = function (effect) {
  97725. this._currentEffect = effect;
  97726. if (effect.onBind) {
  97727. effect.onBind(effect);
  97728. }
  97729. effect.onBindObservable.notifyObservers(effect);
  97730. };
  97731. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  97732. if (zOffset === void 0) { zOffset = 0; }
  97733. if (reverseSide === void 0) { reverseSide = false; }
  97734. };
  97735. NullEngine.prototype.setIntArray = function (uniform, array) {
  97736. };
  97737. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  97738. };
  97739. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  97740. };
  97741. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  97742. };
  97743. NullEngine.prototype.setFloatArray = function (uniform, array) {
  97744. };
  97745. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  97746. };
  97747. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  97748. };
  97749. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  97750. };
  97751. NullEngine.prototype.setArray = function (uniform, array) {
  97752. };
  97753. NullEngine.prototype.setArray2 = function (uniform, array) {
  97754. };
  97755. NullEngine.prototype.setArray3 = function (uniform, array) {
  97756. };
  97757. NullEngine.prototype.setArray4 = function (uniform, array) {
  97758. };
  97759. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  97760. };
  97761. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  97762. };
  97763. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  97764. };
  97765. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  97766. };
  97767. NullEngine.prototype.setFloat = function (uniform, value) {
  97768. };
  97769. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  97770. };
  97771. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  97772. };
  97773. NullEngine.prototype.setBool = function (uniform, bool) {
  97774. };
  97775. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  97776. };
  97777. NullEngine.prototype.setColor3 = function (uniform, color3) {
  97778. };
  97779. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  97780. };
  97781. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  97782. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  97783. if (this._alphaMode === mode) {
  97784. return;
  97785. }
  97786. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  97787. if (!noDepthWriteChange) {
  97788. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  97789. }
  97790. this._alphaMode = mode;
  97791. };
  97792. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  97793. };
  97794. NullEngine.prototype.wipeCaches = function (bruteForce) {
  97795. if (this.preventCacheWipeBetweenFrames) {
  97796. return;
  97797. }
  97798. this.resetTextureCache();
  97799. this._currentEffect = null;
  97800. if (bruteForce) {
  97801. this._currentProgram = null;
  97802. this._stencilState.reset();
  97803. this._depthCullingState.reset();
  97804. this._alphaState.reset();
  97805. }
  97806. this._cachedVertexBuffers = null;
  97807. this._cachedIndexBuffer = null;
  97808. this._cachedEffectForVertexBuffers = null;
  97809. };
  97810. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  97811. };
  97812. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  97813. };
  97814. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  97815. };
  97816. NullEngine.prototype._createTexture = function () {
  97817. return {};
  97818. };
  97819. NullEngine.prototype._releaseTexture = function (texture) {
  97820. };
  97821. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  97822. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97823. if (onLoad === void 0) { onLoad = null; }
  97824. if (onError === void 0) { onError = null; }
  97825. if (buffer === void 0) { buffer = null; }
  97826. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  97827. var url = String(urlArg);
  97828. texture.url = url;
  97829. texture.generateMipMaps = !noMipmap;
  97830. texture.samplingMode = samplingMode;
  97831. texture.invertY = invertY;
  97832. texture.baseWidth = this._options.textureSize;
  97833. texture.baseHeight = this._options.textureSize;
  97834. texture.width = this._options.textureSize;
  97835. texture.height = this._options.textureSize;
  97836. if (format) {
  97837. texture.format = format;
  97838. }
  97839. texture.isReady = true;
  97840. if (onLoad) {
  97841. onLoad();
  97842. }
  97843. this._internalTexturesCache.push(texture);
  97844. return texture;
  97845. };
  97846. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  97847. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  97848. if (options !== undefined && typeof options === "object") {
  97849. fullOptions.generateMipMaps = options.generateMipMaps;
  97850. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  97851. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  97852. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  97853. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  97854. }
  97855. else {
  97856. fullOptions.generateMipMaps = options;
  97857. fullOptions.generateDepthBuffer = true;
  97858. fullOptions.generateStencilBuffer = false;
  97859. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97860. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  97861. }
  97862. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  97863. var width = size.width || size;
  97864. var height = size.height || size;
  97865. texture._depthStencilBuffer = {};
  97866. texture._framebuffer = {};
  97867. texture.baseWidth = width;
  97868. texture.baseHeight = height;
  97869. texture.width = width;
  97870. texture.height = height;
  97871. texture.isReady = true;
  97872. texture.samples = 1;
  97873. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  97874. texture.samplingMode = fullOptions.samplingMode;
  97875. texture.type = fullOptions.type;
  97876. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  97877. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  97878. this._internalTexturesCache.push(texture);
  97879. return texture;
  97880. };
  97881. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  97882. texture.samplingMode = samplingMode;
  97883. };
  97884. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  97885. if (this._currentRenderTarget) {
  97886. this.unBindFramebuffer(this._currentRenderTarget);
  97887. }
  97888. this._currentRenderTarget = texture;
  97889. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  97890. if (this._cachedViewport && !forceFullscreenViewport) {
  97891. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  97892. }
  97893. };
  97894. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  97895. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  97896. this._currentRenderTarget = null;
  97897. if (onBeforeUnbind) {
  97898. if (texture._MSAAFramebuffer) {
  97899. this._currentFramebuffer = texture._framebuffer;
  97900. }
  97901. onBeforeUnbind();
  97902. }
  97903. this._currentFramebuffer = null;
  97904. };
  97905. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  97906. var vbo = {
  97907. capacity: 1,
  97908. references: 1,
  97909. is32Bits: false
  97910. };
  97911. return vbo;
  97912. };
  97913. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  97914. if (offset === void 0) { offset = 0; }
  97915. };
  97916. /**
  97917. * Updates a dynamic vertex buffer.
  97918. * @param vertexBuffer the vertex buffer to update
  97919. * @param data the data used to update the vertex buffer
  97920. * @param byteOffset the byte offset of the data (optional)
  97921. * @param byteLength the byte length of the data (optional)
  97922. */
  97923. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  97924. };
  97925. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  97926. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  97927. this._boundTexturesCache[this._activeChannel] = texture;
  97928. }
  97929. };
  97930. NullEngine.prototype._bindTexture = function (channel, texture) {
  97931. if (channel < 0) {
  97932. return;
  97933. }
  97934. this._bindTextureDirectly(0, texture);
  97935. };
  97936. NullEngine.prototype._releaseBuffer = function (buffer) {
  97937. buffer.references--;
  97938. if (buffer.references === 0) {
  97939. return true;
  97940. }
  97941. return false;
  97942. };
  97943. NullEngine.prototype.releaseEffects = function () {
  97944. };
  97945. return NullEngine;
  97946. }(BABYLON.Engine));
  97947. BABYLON.NullEngine = NullEngine;
  97948. })(BABYLON || (BABYLON = {}));
  97949. //# sourceMappingURL=babylon.nullEngine.js.map
  97950. var BABYLON;
  97951. (function (BABYLON) {
  97952. /**
  97953. * This class can be used to get instrumentation data from a Babylon engine
  97954. */
  97955. var EngineInstrumentation = /** @class */ (function () {
  97956. function EngineInstrumentation(engine) {
  97957. this.engine = engine;
  97958. this._captureGPUFrameTime = false;
  97959. this._gpuFrameTime = new BABYLON.PerfCounter();
  97960. this._captureShaderCompilationTime = false;
  97961. this._shaderCompilationTime = new BABYLON.PerfCounter();
  97962. // Observers
  97963. this._onBeginFrameObserver = null;
  97964. this._onEndFrameObserver = null;
  97965. this._onBeforeShaderCompilationObserver = null;
  97966. this._onAfterShaderCompilationObserver = null;
  97967. }
  97968. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  97969. // Properties
  97970. /**
  97971. * Gets the perf counter used for GPU frame time
  97972. */
  97973. get: function () {
  97974. return this._gpuFrameTime;
  97975. },
  97976. enumerable: true,
  97977. configurable: true
  97978. });
  97979. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  97980. /**
  97981. * Gets the GPU frame time capture status
  97982. */
  97983. get: function () {
  97984. return this._captureGPUFrameTime;
  97985. },
  97986. /**
  97987. * Enable or disable the GPU frame time capture
  97988. */
  97989. set: function (value) {
  97990. var _this = this;
  97991. if (value === this._captureGPUFrameTime) {
  97992. return;
  97993. }
  97994. this._captureGPUFrameTime = value;
  97995. if (value) {
  97996. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  97997. if (!_this._gpuFrameTimeToken) {
  97998. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  97999. }
  98000. });
  98001. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  98002. if (!_this._gpuFrameTimeToken) {
  98003. return;
  98004. }
  98005. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  98006. if (time > -1) {
  98007. _this._gpuFrameTimeToken = null;
  98008. _this._gpuFrameTime.fetchNewFrame();
  98009. _this._gpuFrameTime.addCount(time, true);
  98010. }
  98011. });
  98012. }
  98013. else {
  98014. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  98015. this._onBeginFrameObserver = null;
  98016. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  98017. this._onEndFrameObserver = null;
  98018. }
  98019. },
  98020. enumerable: true,
  98021. configurable: true
  98022. });
  98023. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  98024. /**
  98025. * Gets the perf counter used for shader compilation time
  98026. */
  98027. get: function () {
  98028. return this._shaderCompilationTime;
  98029. },
  98030. enumerable: true,
  98031. configurable: true
  98032. });
  98033. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  98034. /**
  98035. * Gets the shader compilation time capture status
  98036. */
  98037. get: function () {
  98038. return this._captureShaderCompilationTime;
  98039. },
  98040. /**
  98041. * Enable or disable the shader compilation time capture
  98042. */
  98043. set: function (value) {
  98044. var _this = this;
  98045. if (value === this._captureShaderCompilationTime) {
  98046. return;
  98047. }
  98048. this._captureShaderCompilationTime = value;
  98049. if (value) {
  98050. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  98051. _this._shaderCompilationTime.fetchNewFrame();
  98052. _this._shaderCompilationTime.beginMonitoring();
  98053. });
  98054. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  98055. _this._shaderCompilationTime.endMonitoring();
  98056. });
  98057. }
  98058. else {
  98059. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98060. this._onBeforeShaderCompilationObserver = null;
  98061. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98062. this._onAfterShaderCompilationObserver = null;
  98063. }
  98064. },
  98065. enumerable: true,
  98066. configurable: true
  98067. });
  98068. EngineInstrumentation.prototype.dispose = function () {
  98069. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  98070. this._onBeginFrameObserver = null;
  98071. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  98072. this._onEndFrameObserver = null;
  98073. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98074. this._onBeforeShaderCompilationObserver = null;
  98075. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98076. this._onAfterShaderCompilationObserver = null;
  98077. this.engine = null;
  98078. };
  98079. return EngineInstrumentation;
  98080. }());
  98081. BABYLON.EngineInstrumentation = EngineInstrumentation;
  98082. })(BABYLON || (BABYLON = {}));
  98083. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  98084. var BABYLON;
  98085. (function (BABYLON) {
  98086. /**
  98087. * This class can be used to get instrumentation data from a Babylon engine
  98088. */
  98089. var SceneInstrumentation = /** @class */ (function () {
  98090. function SceneInstrumentation(scene) {
  98091. var _this = this;
  98092. this.scene = scene;
  98093. this._captureActiveMeshesEvaluationTime = false;
  98094. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  98095. this._captureRenderTargetsRenderTime = false;
  98096. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  98097. this._captureFrameTime = false;
  98098. this._frameTime = new BABYLON.PerfCounter();
  98099. this._captureRenderTime = false;
  98100. this._renderTime = new BABYLON.PerfCounter();
  98101. this._captureInterFrameTime = false;
  98102. this._interFrameTime = new BABYLON.PerfCounter();
  98103. this._captureParticlesRenderTime = false;
  98104. this._particlesRenderTime = new BABYLON.PerfCounter();
  98105. this._captureSpritesRenderTime = false;
  98106. this._spritesRenderTime = new BABYLON.PerfCounter();
  98107. this._capturePhysicsTime = false;
  98108. this._physicsTime = new BABYLON.PerfCounter();
  98109. this._captureAnimationsTime = false;
  98110. this._animationsTime = new BABYLON.PerfCounter();
  98111. // Observers
  98112. this._onBeforeActiveMeshesEvaluationObserver = null;
  98113. this._onAfterActiveMeshesEvaluationObserver = null;
  98114. this._onBeforeRenderTargetsRenderObserver = null;
  98115. this._onAfterRenderTargetsRenderObserver = null;
  98116. this._onAfterRenderObserver = null;
  98117. this._onBeforeDrawPhaseObserver = null;
  98118. this._onAfterDrawPhaseObserver = null;
  98119. this._onBeforeAnimationsObserver = null;
  98120. this._onBeforeParticlesRenderingObserver = null;
  98121. this._onAfterParticlesRenderingObserver = null;
  98122. this._onBeforeSpritesRenderingObserver = null;
  98123. this._onAfterSpritesRenderingObserver = null;
  98124. this._onBeforePhysicsObserver = null;
  98125. this._onAfterPhysicsObserver = null;
  98126. this._onAfterAnimationsObserver = null;
  98127. // Before render
  98128. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  98129. if (_this._captureActiveMeshesEvaluationTime) {
  98130. _this._activeMeshesEvaluationTime.fetchNewFrame();
  98131. }
  98132. if (_this._captureRenderTargetsRenderTime) {
  98133. _this._renderTargetsRenderTime.fetchNewFrame();
  98134. }
  98135. if (_this._captureFrameTime) {
  98136. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  98137. _this._frameTime.beginMonitoring();
  98138. }
  98139. if (_this._captureInterFrameTime) {
  98140. _this._interFrameTime.endMonitoring();
  98141. }
  98142. if (_this._captureParticlesRenderTime) {
  98143. _this._particlesRenderTime.fetchNewFrame();
  98144. }
  98145. if (_this._captureSpritesRenderTime) {
  98146. _this._spritesRenderTime.fetchNewFrame();
  98147. }
  98148. if (_this._captureAnimationsTime) {
  98149. _this._animationsTime.beginMonitoring();
  98150. }
  98151. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  98152. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  98153. });
  98154. // After render
  98155. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  98156. if (_this._captureFrameTime) {
  98157. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  98158. _this._frameTime.endMonitoring();
  98159. }
  98160. if (_this._captureRenderTime) {
  98161. _this._renderTime.endMonitoring(false);
  98162. }
  98163. if (_this._captureInterFrameTime) {
  98164. _this._interFrameTime.beginMonitoring();
  98165. }
  98166. });
  98167. }
  98168. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  98169. // Properties
  98170. /**
  98171. * Gets the perf counter used for active meshes evaluation time
  98172. */
  98173. get: function () {
  98174. return this._activeMeshesEvaluationTime;
  98175. },
  98176. enumerable: true,
  98177. configurable: true
  98178. });
  98179. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  98180. /**
  98181. * Gets the active meshes evaluation time capture status
  98182. */
  98183. get: function () {
  98184. return this._captureActiveMeshesEvaluationTime;
  98185. },
  98186. /**
  98187. * Enable or disable the active meshes evaluation time capture
  98188. */
  98189. set: function (value) {
  98190. var _this = this;
  98191. if (value === this._captureActiveMeshesEvaluationTime) {
  98192. return;
  98193. }
  98194. this._captureActiveMeshesEvaluationTime = value;
  98195. if (value) {
  98196. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  98197. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  98198. _this._activeMeshesEvaluationTime.beginMonitoring();
  98199. });
  98200. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  98201. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  98202. _this._activeMeshesEvaluationTime.endMonitoring();
  98203. });
  98204. }
  98205. else {
  98206. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98207. this._onBeforeActiveMeshesEvaluationObserver = null;
  98208. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98209. this._onAfterActiveMeshesEvaluationObserver = null;
  98210. }
  98211. },
  98212. enumerable: true,
  98213. configurable: true
  98214. });
  98215. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  98216. /**
  98217. * Gets the perf counter used for render targets render time
  98218. */
  98219. get: function () {
  98220. return this._renderTargetsRenderTime;
  98221. },
  98222. enumerable: true,
  98223. configurable: true
  98224. });
  98225. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  98226. /**
  98227. * Gets the render targets render time capture status
  98228. */
  98229. get: function () {
  98230. return this._captureRenderTargetsRenderTime;
  98231. },
  98232. /**
  98233. * Enable or disable the render targets render time capture
  98234. */
  98235. set: function (value) {
  98236. var _this = this;
  98237. if (value === this._captureRenderTargetsRenderTime) {
  98238. return;
  98239. }
  98240. this._captureRenderTargetsRenderTime = value;
  98241. if (value) {
  98242. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  98243. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  98244. _this._renderTargetsRenderTime.beginMonitoring();
  98245. });
  98246. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  98247. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  98248. _this._renderTargetsRenderTime.endMonitoring(false);
  98249. });
  98250. }
  98251. else {
  98252. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98253. this._onBeforeRenderTargetsRenderObserver = null;
  98254. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98255. this._onAfterRenderTargetsRenderObserver = null;
  98256. }
  98257. },
  98258. enumerable: true,
  98259. configurable: true
  98260. });
  98261. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  98262. /**
  98263. * Gets the perf counter used for particles render time
  98264. */
  98265. get: function () {
  98266. return this._particlesRenderTime;
  98267. },
  98268. enumerable: true,
  98269. configurable: true
  98270. });
  98271. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  98272. /**
  98273. * Gets the particles render time capture status
  98274. */
  98275. get: function () {
  98276. return this._captureParticlesRenderTime;
  98277. },
  98278. /**
  98279. * Enable or disable the particles render time capture
  98280. */
  98281. set: function (value) {
  98282. var _this = this;
  98283. if (value === this._captureParticlesRenderTime) {
  98284. return;
  98285. }
  98286. this._captureParticlesRenderTime = value;
  98287. if (value) {
  98288. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  98289. BABYLON.Tools.StartPerformanceCounter("Particles");
  98290. _this._particlesRenderTime.beginMonitoring();
  98291. });
  98292. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  98293. BABYLON.Tools.EndPerformanceCounter("Particles");
  98294. _this._particlesRenderTime.endMonitoring(false);
  98295. });
  98296. }
  98297. else {
  98298. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98299. this._onBeforeParticlesRenderingObserver = null;
  98300. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98301. this._onAfterParticlesRenderingObserver = null;
  98302. }
  98303. },
  98304. enumerable: true,
  98305. configurable: true
  98306. });
  98307. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  98308. /**
  98309. * Gets the perf counter used for sprites render time
  98310. */
  98311. get: function () {
  98312. return this._spritesRenderTime;
  98313. },
  98314. enumerable: true,
  98315. configurable: true
  98316. });
  98317. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  98318. /**
  98319. * Gets the sprites render time capture status
  98320. */
  98321. get: function () {
  98322. return this._captureSpritesRenderTime;
  98323. },
  98324. /**
  98325. * Enable or disable the sprites render time capture
  98326. */
  98327. set: function (value) {
  98328. var _this = this;
  98329. if (value === this._captureSpritesRenderTime) {
  98330. return;
  98331. }
  98332. this._captureSpritesRenderTime = value;
  98333. if (value) {
  98334. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  98335. BABYLON.Tools.StartPerformanceCounter("Sprites");
  98336. _this._spritesRenderTime.beginMonitoring();
  98337. });
  98338. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  98339. BABYLON.Tools.EndPerformanceCounter("Sprites");
  98340. _this._spritesRenderTime.endMonitoring(false);
  98341. });
  98342. }
  98343. else {
  98344. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98345. this._onBeforeSpritesRenderingObserver = null;
  98346. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98347. this._onAfterSpritesRenderingObserver = null;
  98348. }
  98349. },
  98350. enumerable: true,
  98351. configurable: true
  98352. });
  98353. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  98354. /**
  98355. * Gets the perf counter used for physics time
  98356. */
  98357. get: function () {
  98358. return this._physicsTime;
  98359. },
  98360. enumerable: true,
  98361. configurable: true
  98362. });
  98363. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  98364. /**
  98365. * Gets the physics time capture status
  98366. */
  98367. get: function () {
  98368. return this._capturePhysicsTime;
  98369. },
  98370. /**
  98371. * Enable or disable the physics time capture
  98372. */
  98373. set: function (value) {
  98374. var _this = this;
  98375. if (value === this._capturePhysicsTime) {
  98376. return;
  98377. }
  98378. this._capturePhysicsTime = value;
  98379. if (value) {
  98380. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  98381. BABYLON.Tools.StartPerformanceCounter("Physics");
  98382. _this._physicsTime.beginMonitoring();
  98383. });
  98384. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  98385. BABYLON.Tools.EndPerformanceCounter("Physics");
  98386. _this._physicsTime.endMonitoring();
  98387. });
  98388. }
  98389. else {
  98390. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98391. this._onBeforePhysicsObserver = null;
  98392. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98393. this._onAfterPhysicsObserver = null;
  98394. }
  98395. },
  98396. enumerable: true,
  98397. configurable: true
  98398. });
  98399. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  98400. /**
  98401. * Gets the perf counter used for animations time
  98402. */
  98403. get: function () {
  98404. return this._animationsTime;
  98405. },
  98406. enumerable: true,
  98407. configurable: true
  98408. });
  98409. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  98410. /**
  98411. * Gets the animations time capture status
  98412. */
  98413. get: function () {
  98414. return this._captureAnimationsTime;
  98415. },
  98416. /**
  98417. * Enable or disable the animations time capture
  98418. */
  98419. set: function (value) {
  98420. var _this = this;
  98421. if (value === this._captureAnimationsTime) {
  98422. return;
  98423. }
  98424. this._captureAnimationsTime = value;
  98425. if (value) {
  98426. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  98427. _this._animationsTime.endMonitoring();
  98428. });
  98429. }
  98430. else {
  98431. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98432. this._onAfterAnimationsObserver = null;
  98433. }
  98434. },
  98435. enumerable: true,
  98436. configurable: true
  98437. });
  98438. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  98439. /**
  98440. * Gets the perf counter used for frame time capture
  98441. */
  98442. get: function () {
  98443. return this._frameTime;
  98444. },
  98445. enumerable: true,
  98446. configurable: true
  98447. });
  98448. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  98449. /**
  98450. * Gets the frame time capture status
  98451. */
  98452. get: function () {
  98453. return this._captureFrameTime;
  98454. },
  98455. /**
  98456. * Enable or disable the frame time capture
  98457. */
  98458. set: function (value) {
  98459. this._captureFrameTime = value;
  98460. },
  98461. enumerable: true,
  98462. configurable: true
  98463. });
  98464. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  98465. /**
  98466. * Gets the perf counter used for inter-frames time capture
  98467. */
  98468. get: function () {
  98469. return this._interFrameTime;
  98470. },
  98471. enumerable: true,
  98472. configurable: true
  98473. });
  98474. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  98475. /**
  98476. * Gets the inter-frames time capture status
  98477. */
  98478. get: function () {
  98479. return this._captureInterFrameTime;
  98480. },
  98481. /**
  98482. * Enable or disable the inter-frames time capture
  98483. */
  98484. set: function (value) {
  98485. this._captureInterFrameTime = value;
  98486. },
  98487. enumerable: true,
  98488. configurable: true
  98489. });
  98490. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  98491. /**
  98492. * Gets the perf counter used for render time capture
  98493. */
  98494. get: function () {
  98495. return this._renderTime;
  98496. },
  98497. enumerable: true,
  98498. configurable: true
  98499. });
  98500. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  98501. /**
  98502. * Gets the render time capture status
  98503. */
  98504. get: function () {
  98505. return this._captureRenderTime;
  98506. },
  98507. /**
  98508. * Enable or disable the render time capture
  98509. */
  98510. set: function (value) {
  98511. var _this = this;
  98512. if (value === this._captureRenderTime) {
  98513. return;
  98514. }
  98515. this._captureRenderTime = value;
  98516. if (value) {
  98517. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  98518. _this._renderTime.beginMonitoring();
  98519. BABYLON.Tools.StartPerformanceCounter("Main render");
  98520. });
  98521. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  98522. _this._renderTime.endMonitoring(false);
  98523. BABYLON.Tools.EndPerformanceCounter("Main render");
  98524. });
  98525. }
  98526. else {
  98527. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98528. this._onBeforeDrawPhaseObserver = null;
  98529. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98530. this._onAfterDrawPhaseObserver = null;
  98531. }
  98532. },
  98533. enumerable: true,
  98534. configurable: true
  98535. });
  98536. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  98537. /**
  98538. * Gets the perf counter used for draw calls
  98539. */
  98540. get: function () {
  98541. return this.scene.getEngine()._drawCalls;
  98542. },
  98543. enumerable: true,
  98544. configurable: true
  98545. });
  98546. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  98547. /**
  98548. * Gets the perf counter used for texture collisions
  98549. */
  98550. get: function () {
  98551. return this.scene.getEngine()._textureCollisions;
  98552. },
  98553. enumerable: true,
  98554. configurable: true
  98555. });
  98556. SceneInstrumentation.prototype.dispose = function () {
  98557. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98558. this._onAfterRenderObserver = null;
  98559. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98560. this._onBeforeActiveMeshesEvaluationObserver = null;
  98561. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98562. this._onAfterActiveMeshesEvaluationObserver = null;
  98563. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98564. this._onBeforeRenderTargetsRenderObserver = null;
  98565. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98566. this._onAfterRenderTargetsRenderObserver = null;
  98567. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  98568. this._onBeforeAnimationsObserver = null;
  98569. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98570. this._onBeforeParticlesRenderingObserver = null;
  98571. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98572. this._onAfterParticlesRenderingObserver = null;
  98573. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98574. this._onBeforeSpritesRenderingObserver = null;
  98575. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98576. this._onAfterSpritesRenderingObserver = null;
  98577. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98578. this._onBeforeDrawPhaseObserver = null;
  98579. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98580. this._onAfterDrawPhaseObserver = null;
  98581. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98582. this._onBeforePhysicsObserver = null;
  98583. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98584. this._onAfterPhysicsObserver = null;
  98585. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98586. this._onAfterAnimationsObserver = null;
  98587. this.scene = null;
  98588. };
  98589. return SceneInstrumentation;
  98590. }());
  98591. BABYLON.SceneInstrumentation = SceneInstrumentation;
  98592. })(BABYLON || (BABYLON = {}));
  98593. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  98594. var BABYLON;
  98595. (function (BABYLON) {
  98596. /**
  98597. * @hidden
  98598. **/
  98599. var _TimeToken = /** @class */ (function () {
  98600. function _TimeToken() {
  98601. this._timeElapsedQueryEnded = false;
  98602. }
  98603. return _TimeToken;
  98604. }());
  98605. BABYLON._TimeToken = _TimeToken;
  98606. })(BABYLON || (BABYLON = {}));
  98607. //# sourceMappingURL=babylon.timeToken.js.map
  98608. var BABYLON;
  98609. (function (BABYLON) {
  98610. /**
  98611. * Background material defines definition.
  98612. * @hidden Mainly internal Use
  98613. */
  98614. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  98615. __extends(BackgroundMaterialDefines, _super);
  98616. /**
  98617. * Constructor of the defines.
  98618. */
  98619. function BackgroundMaterialDefines() {
  98620. var _this = _super.call(this) || this;
  98621. /**
  98622. * True if the diffuse texture is in use.
  98623. */
  98624. _this.DIFFUSE = false;
  98625. /**
  98626. * The direct UV channel to use.
  98627. */
  98628. _this.DIFFUSEDIRECTUV = 0;
  98629. /**
  98630. * True if the diffuse texture is in gamma space.
  98631. */
  98632. _this.GAMMADIFFUSE = false;
  98633. /**
  98634. * True if the diffuse texture has opacity in the alpha channel.
  98635. */
  98636. _this.DIFFUSEHASALPHA = false;
  98637. /**
  98638. * True if you want the material to fade to transparent at grazing angle.
  98639. */
  98640. _this.OPACITYFRESNEL = false;
  98641. /**
  98642. * True if an extra blur needs to be added in the reflection.
  98643. */
  98644. _this.REFLECTIONBLUR = false;
  98645. /**
  98646. * True if you want the material to fade to reflection at grazing angle.
  98647. */
  98648. _this.REFLECTIONFRESNEL = false;
  98649. /**
  98650. * True if you want the material to falloff as far as you move away from the scene center.
  98651. */
  98652. _this.REFLECTIONFALLOFF = false;
  98653. /**
  98654. * False if the current Webgl implementation does not support the texture lod extension.
  98655. */
  98656. _this.TEXTURELODSUPPORT = false;
  98657. /**
  98658. * True to ensure the data are premultiplied.
  98659. */
  98660. _this.PREMULTIPLYALPHA = false;
  98661. /**
  98662. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  98663. */
  98664. _this.USERGBCOLOR = false;
  98665. /**
  98666. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  98667. * stays aligned with the desired configuration.
  98668. */
  98669. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  98670. /**
  98671. * True to add noise in order to reduce the banding effect.
  98672. */
  98673. _this.NOISE = false;
  98674. /**
  98675. * is the reflection texture in BGR color scheme?
  98676. * Mainly used to solve a bug in ios10 video tag
  98677. */
  98678. _this.REFLECTIONBGR = false;
  98679. _this.IMAGEPROCESSING = false;
  98680. _this.VIGNETTE = false;
  98681. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  98682. _this.VIGNETTEBLENDMODEOPAQUE = false;
  98683. _this.TONEMAPPING = false;
  98684. _this.CONTRAST = false;
  98685. _this.COLORCURVES = false;
  98686. _this.COLORGRADING = false;
  98687. _this.COLORGRADING3D = false;
  98688. _this.SAMPLER3DGREENDEPTH = false;
  98689. _this.SAMPLER3DBGRMAP = false;
  98690. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  98691. _this.EXPOSURE = false;
  98692. // Reflection.
  98693. _this.REFLECTION = false;
  98694. _this.REFLECTIONMAP_3D = false;
  98695. _this.REFLECTIONMAP_SPHERICAL = false;
  98696. _this.REFLECTIONMAP_PLANAR = false;
  98697. _this.REFLECTIONMAP_CUBIC = false;
  98698. _this.REFLECTIONMAP_PROJECTION = false;
  98699. _this.REFLECTIONMAP_SKYBOX = false;
  98700. _this.REFLECTIONMAP_EXPLICIT = false;
  98701. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98702. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98703. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98704. _this.INVERTCUBICMAP = false;
  98705. _this.REFLECTIONMAP_OPPOSITEZ = false;
  98706. _this.LODINREFLECTIONALPHA = false;
  98707. _this.GAMMAREFLECTION = false;
  98708. _this.RGBDREFLECTION = false;
  98709. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  98710. // Default BJS.
  98711. _this.MAINUV1 = false;
  98712. _this.MAINUV2 = false;
  98713. _this.UV1 = false;
  98714. _this.UV2 = false;
  98715. _this.CLIPPLANE = false;
  98716. _this.POINTSIZE = false;
  98717. _this.FOG = false;
  98718. _this.NORMAL = false;
  98719. _this.NUM_BONE_INFLUENCERS = 0;
  98720. _this.BonesPerMesh = 0;
  98721. _this.INSTANCES = false;
  98722. _this.SHADOWFLOAT = false;
  98723. _this.rebuild();
  98724. return _this;
  98725. }
  98726. return BackgroundMaterialDefines;
  98727. }(BABYLON.MaterialDefines));
  98728. /**
  98729. * Background material used to create an efficient environement around your scene.
  98730. */
  98731. var BackgroundMaterial = /** @class */ (function (_super) {
  98732. __extends(BackgroundMaterial, _super);
  98733. /**
  98734. * Instantiates a Background Material in the given scene
  98735. * @param name The friendly name of the material
  98736. * @param scene The scene to add the material to
  98737. */
  98738. function BackgroundMaterial(name, scene) {
  98739. var _this = _super.call(this, name, scene) || this;
  98740. /**
  98741. * Key light Color (multiply against the environement texture)
  98742. */
  98743. _this.primaryColor = BABYLON.Color3.White();
  98744. _this._primaryColorShadowLevel = 0;
  98745. _this._primaryColorHighlightLevel = 0;
  98746. /**
  98747. * Reflection Texture used in the material.
  98748. * Should be author in a specific way for the best result (refer to the documentation).
  98749. */
  98750. _this.reflectionTexture = null;
  98751. /**
  98752. * Reflection Texture level of blur.
  98753. *
  98754. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  98755. * texture twice.
  98756. */
  98757. _this.reflectionBlur = 0;
  98758. /**
  98759. * Diffuse Texture used in the material.
  98760. * Should be author in a specific way for the best result (refer to the documentation).
  98761. */
  98762. _this.diffuseTexture = null;
  98763. _this._shadowLights = null;
  98764. /**
  98765. * Specify the list of lights casting shadow on the material.
  98766. * All scene shadow lights will be included if null.
  98767. */
  98768. _this.shadowLights = null;
  98769. /**
  98770. * Helps adjusting the shadow to a softer level if required.
  98771. * 0 means black shadows and 1 means no shadows.
  98772. */
  98773. _this.shadowLevel = 0;
  98774. /**
  98775. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  98776. * It is usually zero but might be interesting to modify according to your setup.
  98777. */
  98778. _this.sceneCenter = BABYLON.Vector3.Zero();
  98779. /**
  98780. * This helps specifying that the material is falling off to the sky box at grazing angle.
  98781. * This helps ensuring a nice transition when the camera goes under the ground.
  98782. */
  98783. _this.opacityFresnel = true;
  98784. /**
  98785. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  98786. * This helps adding a mirror texture on the ground.
  98787. */
  98788. _this.reflectionFresnel = false;
  98789. /**
  98790. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  98791. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  98792. */
  98793. _this.reflectionFalloffDistance = 0.0;
  98794. /**
  98795. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  98796. */
  98797. _this.reflectionAmount = 1.0;
  98798. /**
  98799. * This specifies the weight of the reflection at grazing angle.
  98800. */
  98801. _this.reflectionReflectance0 = 0.05;
  98802. /**
  98803. * This specifies the weight of the reflection at a perpendicular point of view.
  98804. */
  98805. _this.reflectionReflectance90 = 0.5;
  98806. /**
  98807. * Helps to directly use the maps channels instead of their level.
  98808. */
  98809. _this.useRGBColor = true;
  98810. /**
  98811. * This helps reducing the banding effect that could occur on the background.
  98812. */
  98813. _this.enableNoise = false;
  98814. _this._fovMultiplier = 1.0;
  98815. /**
  98816. * Enable the FOV adjustment feature controlled by fovMultiplier.
  98817. */
  98818. _this.useEquirectangularFOV = false;
  98819. _this._maxSimultaneousLights = 4;
  98820. /**
  98821. * Number of Simultaneous lights allowed on the material.
  98822. */
  98823. _this.maxSimultaneousLights = 4;
  98824. /**
  98825. * Keep track of the image processing observer to allow dispose and replace.
  98826. */
  98827. _this._imageProcessingObserver = null;
  98828. /**
  98829. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  98830. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  98831. */
  98832. _this.switchToBGR = false;
  98833. // Temp values kept as cache in the material.
  98834. _this._renderTargets = new BABYLON.SmartArray(16);
  98835. _this._reflectionControls = BABYLON.Vector4.Zero();
  98836. _this._white = BABYLON.Color3.White();
  98837. _this._primaryShadowColor = BABYLON.Color3.Black();
  98838. _this._primaryHighlightColor = BABYLON.Color3.Black();
  98839. // Setup the default processing configuration to the scene.
  98840. _this._attachImageProcessingConfiguration(null);
  98841. _this.getRenderTargetTextures = function () {
  98842. _this._renderTargets.reset();
  98843. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  98844. _this._renderTargets.push(_this._diffuseTexture);
  98845. }
  98846. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  98847. _this._renderTargets.push(_this._reflectionTexture);
  98848. }
  98849. return _this._renderTargets;
  98850. };
  98851. return _this;
  98852. }
  98853. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  98854. /**
  98855. * Experimental Internal Use Only.
  98856. *
  98857. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  98858. * This acts as a helper to set the primary color to a more "human friendly" value.
  98859. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  98860. * output color as close as possible from the chosen value.
  98861. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  98862. * part of lighting setup.)
  98863. */
  98864. get: function () {
  98865. return this.__perceptualColor;
  98866. },
  98867. set: function (value) {
  98868. this.__perceptualColor = value;
  98869. this._computePrimaryColorFromPerceptualColor();
  98870. this._markAllSubMeshesAsLightsDirty();
  98871. },
  98872. enumerable: true,
  98873. configurable: true
  98874. });
  98875. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  98876. /**
  98877. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  98878. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  98879. */
  98880. get: function () {
  98881. return this._primaryColorShadowLevel;
  98882. },
  98883. set: function (value) {
  98884. this._primaryColorShadowLevel = value;
  98885. this._computePrimaryColors();
  98886. this._markAllSubMeshesAsLightsDirty();
  98887. },
  98888. enumerable: true,
  98889. configurable: true
  98890. });
  98891. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  98892. /**
  98893. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  98894. * The primary color is used at the level chosen to define what the white area would look.
  98895. */
  98896. get: function () {
  98897. return this._primaryColorHighlightLevel;
  98898. },
  98899. set: function (value) {
  98900. this._primaryColorHighlightLevel = value;
  98901. this._computePrimaryColors();
  98902. this._markAllSubMeshesAsLightsDirty();
  98903. },
  98904. enumerable: true,
  98905. configurable: true
  98906. });
  98907. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  98908. /**
  98909. * Sets the reflection reflectance fresnel values according to the default standard
  98910. * empirically know to work well :-)
  98911. */
  98912. set: function (value) {
  98913. var reflectionWeight = value;
  98914. if (reflectionWeight < 0.5) {
  98915. reflectionWeight = reflectionWeight * 2.0;
  98916. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  98917. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  98918. }
  98919. else {
  98920. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  98921. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  98922. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  98923. }
  98924. },
  98925. enumerable: true,
  98926. configurable: true
  98927. });
  98928. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  98929. /**
  98930. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98931. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  98932. * Recommended to be keep at 1.0 except for special cases.
  98933. */
  98934. get: function () {
  98935. return this._fovMultiplier;
  98936. },
  98937. set: function (value) {
  98938. if (isNaN(value)) {
  98939. value = 1.0;
  98940. }
  98941. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  98942. },
  98943. enumerable: true,
  98944. configurable: true
  98945. });
  98946. /**
  98947. * Attaches a new image processing configuration to the PBR Material.
  98948. * @param configuration (if null the scene configuration will be use)
  98949. */
  98950. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  98951. var _this = this;
  98952. if (configuration === this._imageProcessingConfiguration) {
  98953. return;
  98954. }
  98955. // Detaches observer.
  98956. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  98957. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  98958. }
  98959. // Pick the scene configuration if needed.
  98960. if (!configuration) {
  98961. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  98962. }
  98963. else {
  98964. this._imageProcessingConfiguration = configuration;
  98965. }
  98966. // Attaches observer.
  98967. if (this._imageProcessingConfiguration) {
  98968. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  98969. _this._computePrimaryColorFromPerceptualColor();
  98970. _this._markAllSubMeshesAsImageProcessingDirty();
  98971. });
  98972. }
  98973. };
  98974. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  98975. /**
  98976. * Gets the image processing configuration used either in this material.
  98977. */
  98978. get: function () {
  98979. return this._imageProcessingConfiguration;
  98980. },
  98981. /**
  98982. * Sets the Default image processing configuration used either in the this material.
  98983. *
  98984. * If sets to null, the scene one is in use.
  98985. */
  98986. set: function (value) {
  98987. this._attachImageProcessingConfiguration(value);
  98988. // Ensure the effect will be rebuilt.
  98989. this._markAllSubMeshesAsTexturesDirty();
  98990. },
  98991. enumerable: true,
  98992. configurable: true
  98993. });
  98994. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  98995. /**
  98996. * Gets wether the color curves effect is enabled.
  98997. */
  98998. get: function () {
  98999. return this.imageProcessingConfiguration.colorCurvesEnabled;
  99000. },
  99001. /**
  99002. * Sets wether the color curves effect is enabled.
  99003. */
  99004. set: function (value) {
  99005. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  99006. },
  99007. enumerable: true,
  99008. configurable: true
  99009. });
  99010. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  99011. /**
  99012. * Gets wether the color grading effect is enabled.
  99013. */
  99014. get: function () {
  99015. return this.imageProcessingConfiguration.colorGradingEnabled;
  99016. },
  99017. /**
  99018. * Gets wether the color grading effect is enabled.
  99019. */
  99020. set: function (value) {
  99021. this.imageProcessingConfiguration.colorGradingEnabled = value;
  99022. },
  99023. enumerable: true,
  99024. configurable: true
  99025. });
  99026. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  99027. /**
  99028. * Gets wether tonemapping is enabled or not.
  99029. */
  99030. get: function () {
  99031. return this._imageProcessingConfiguration.toneMappingEnabled;
  99032. },
  99033. /**
  99034. * Sets wether tonemapping is enabled or not
  99035. */
  99036. set: function (value) {
  99037. this._imageProcessingConfiguration.toneMappingEnabled = value;
  99038. },
  99039. enumerable: true,
  99040. configurable: true
  99041. });
  99042. ;
  99043. ;
  99044. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  99045. /**
  99046. * The camera exposure used on this material.
  99047. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99048. * This corresponds to a photographic exposure.
  99049. */
  99050. get: function () {
  99051. return this._imageProcessingConfiguration.exposure;
  99052. },
  99053. /**
  99054. * The camera exposure used on this material.
  99055. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99056. * This corresponds to a photographic exposure.
  99057. */
  99058. set: function (value) {
  99059. this._imageProcessingConfiguration.exposure = value;
  99060. },
  99061. enumerable: true,
  99062. configurable: true
  99063. });
  99064. ;
  99065. ;
  99066. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  99067. /**
  99068. * Gets The camera contrast used on this material.
  99069. */
  99070. get: function () {
  99071. return this._imageProcessingConfiguration.contrast;
  99072. },
  99073. /**
  99074. * Sets The camera contrast used on this material.
  99075. */
  99076. set: function (value) {
  99077. this._imageProcessingConfiguration.contrast = value;
  99078. },
  99079. enumerable: true,
  99080. configurable: true
  99081. });
  99082. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  99083. /**
  99084. * Gets the Color Grading 2D Lookup Texture.
  99085. */
  99086. get: function () {
  99087. return this._imageProcessingConfiguration.colorGradingTexture;
  99088. },
  99089. /**
  99090. * Sets the Color Grading 2D Lookup Texture.
  99091. */
  99092. set: function (value) {
  99093. this.imageProcessingConfiguration.colorGradingTexture = value;
  99094. },
  99095. enumerable: true,
  99096. configurable: true
  99097. });
  99098. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  99099. /**
  99100. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  99101. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  99102. * 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;
  99103. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  99104. */
  99105. get: function () {
  99106. return this.imageProcessingConfiguration.colorCurves;
  99107. },
  99108. /**
  99109. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  99110. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  99111. * 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;
  99112. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  99113. */
  99114. set: function (value) {
  99115. this.imageProcessingConfiguration.colorCurves = value;
  99116. },
  99117. enumerable: true,
  99118. configurable: true
  99119. });
  99120. /**
  99121. * The entire material has been created in order to prevent overdraw.
  99122. * @returns false
  99123. */
  99124. BackgroundMaterial.prototype.needAlphaTesting = function () {
  99125. return true;
  99126. };
  99127. /**
  99128. * The entire material has been created in order to prevent overdraw.
  99129. * @returns true if blending is enable
  99130. */
  99131. BackgroundMaterial.prototype.needAlphaBlending = function () {
  99132. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  99133. };
  99134. /**
  99135. * Checks wether the material is ready to be rendered for a given mesh.
  99136. * @param mesh The mesh to render
  99137. * @param subMesh The submesh to check against
  99138. * @param useInstances Specify wether or not the material is used with instances
  99139. * @returns true if all the dependencies are ready (Textures, Effects...)
  99140. */
  99141. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  99142. var _this = this;
  99143. if (useInstances === void 0) { useInstances = false; }
  99144. if (subMesh.effect && this.isFrozen) {
  99145. if (this._wasPreviouslyReady) {
  99146. return true;
  99147. }
  99148. }
  99149. if (!subMesh._materialDefines) {
  99150. subMesh._materialDefines = new BackgroundMaterialDefines();
  99151. }
  99152. var scene = this.getScene();
  99153. var defines = subMesh._materialDefines;
  99154. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  99155. if (defines._renderId === scene.getRenderId()) {
  99156. return true;
  99157. }
  99158. }
  99159. var engine = scene.getEngine();
  99160. // Lights
  99161. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  99162. defines._needNormals = true;
  99163. // Textures
  99164. if (defines._areTexturesDirty) {
  99165. defines._needUVs = false;
  99166. if (scene.texturesEnabled) {
  99167. if (scene.getEngine().getCaps().textureLOD) {
  99168. defines.TEXTURELODSUPPORT = true;
  99169. }
  99170. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99171. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  99172. return false;
  99173. }
  99174. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  99175. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  99176. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  99177. defines.OPACITYFRESNEL = this._opacityFresnel;
  99178. }
  99179. else {
  99180. defines.DIFFUSE = false;
  99181. defines.DIFFUSEHASALPHA = false;
  99182. defines.GAMMADIFFUSE = false;
  99183. defines.OPACITYFRESNEL = false;
  99184. }
  99185. var reflectionTexture = this._reflectionTexture;
  99186. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99187. if (!reflectionTexture.isReadyOrNotBlocking()) {
  99188. return false;
  99189. }
  99190. defines.REFLECTION = true;
  99191. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  99192. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  99193. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  99194. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  99195. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  99196. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  99197. defines.REFLECTIONBGR = this.switchToBGR;
  99198. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  99199. defines.INVERTCUBICMAP = true;
  99200. }
  99201. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  99202. switch (reflectionTexture.coordinatesMode) {
  99203. case BABYLON.Texture.EXPLICIT_MODE:
  99204. defines.REFLECTIONMAP_EXPLICIT = true;
  99205. break;
  99206. case BABYLON.Texture.PLANAR_MODE:
  99207. defines.REFLECTIONMAP_PLANAR = true;
  99208. break;
  99209. case BABYLON.Texture.PROJECTION_MODE:
  99210. defines.REFLECTIONMAP_PROJECTION = true;
  99211. break;
  99212. case BABYLON.Texture.SKYBOX_MODE:
  99213. defines.REFLECTIONMAP_SKYBOX = true;
  99214. break;
  99215. case BABYLON.Texture.SPHERICAL_MODE:
  99216. defines.REFLECTIONMAP_SPHERICAL = true;
  99217. break;
  99218. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  99219. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  99220. break;
  99221. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  99222. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  99223. break;
  99224. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  99225. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  99226. break;
  99227. case BABYLON.Texture.CUBIC_MODE:
  99228. case BABYLON.Texture.INVCUBIC_MODE:
  99229. default:
  99230. defines.REFLECTIONMAP_CUBIC = true;
  99231. break;
  99232. }
  99233. if (this.reflectionFresnel) {
  99234. defines.REFLECTIONFRESNEL = true;
  99235. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  99236. this._reflectionControls.x = this.reflectionAmount;
  99237. this._reflectionControls.y = this.reflectionReflectance0;
  99238. this._reflectionControls.z = this.reflectionReflectance90;
  99239. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  99240. }
  99241. else {
  99242. defines.REFLECTIONFRESNEL = false;
  99243. defines.REFLECTIONFALLOFF = false;
  99244. }
  99245. }
  99246. else {
  99247. defines.REFLECTION = false;
  99248. defines.REFLECTIONFRESNEL = false;
  99249. defines.REFLECTIONFALLOFF = false;
  99250. defines.REFLECTIONBLUR = false;
  99251. defines.REFLECTIONMAP_3D = false;
  99252. defines.REFLECTIONMAP_SPHERICAL = false;
  99253. defines.REFLECTIONMAP_PLANAR = false;
  99254. defines.REFLECTIONMAP_CUBIC = false;
  99255. defines.REFLECTIONMAP_PROJECTION = false;
  99256. defines.REFLECTIONMAP_SKYBOX = false;
  99257. defines.REFLECTIONMAP_EXPLICIT = false;
  99258. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  99259. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  99260. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  99261. defines.INVERTCUBICMAP = false;
  99262. defines.REFLECTIONMAP_OPPOSITEZ = false;
  99263. defines.LODINREFLECTIONALPHA = false;
  99264. defines.GAMMAREFLECTION = false;
  99265. defines.RGBDREFLECTION = false;
  99266. }
  99267. }
  99268. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  99269. defines.USERGBCOLOR = this._useRGBColor;
  99270. defines.NOISE = this._enableNoise;
  99271. }
  99272. if (defines._areLightsDirty) {
  99273. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  99274. }
  99275. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  99276. if (!this._imageProcessingConfiguration.isReady()) {
  99277. return false;
  99278. }
  99279. this._imageProcessingConfiguration.prepareDefines(defines);
  99280. }
  99281. // Misc.
  99282. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  99283. // Values that need to be evaluated on every frame
  99284. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  99285. // Attribs
  99286. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  99287. if (mesh) {
  99288. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  99289. mesh.createNormals(true);
  99290. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  99291. }
  99292. }
  99293. }
  99294. // Get correct effect
  99295. if (defines.isDirty) {
  99296. defines.markAsProcessed();
  99297. scene.resetCachedMaterial();
  99298. // Fallbacks
  99299. var fallbacks = new BABYLON.EffectFallbacks();
  99300. if (defines.FOG) {
  99301. fallbacks.addFallback(0, "FOG");
  99302. }
  99303. if (defines.POINTSIZE) {
  99304. fallbacks.addFallback(1, "POINTSIZE");
  99305. }
  99306. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  99307. if (defines.NUM_BONE_INFLUENCERS > 0) {
  99308. fallbacks.addCPUSkinningFallback(0, mesh);
  99309. }
  99310. //Attributes
  99311. var attribs = [BABYLON.VertexBuffer.PositionKind];
  99312. if (defines.NORMAL) {
  99313. attribs.push(BABYLON.VertexBuffer.NormalKind);
  99314. }
  99315. if (defines.UV1) {
  99316. attribs.push(BABYLON.VertexBuffer.UVKind);
  99317. }
  99318. if (defines.UV2) {
  99319. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99320. }
  99321. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  99322. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  99323. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  99324. "vFogInfos", "vFogColor", "pointSize",
  99325. "vClipPlane", "mBones",
  99326. "vPrimaryColor", "vPrimaryColorShadow",
  99327. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  99328. "shadowLevel", "alpha",
  99329. "vBackgroundCenter", "vReflectionControl",
  99330. "vDiffuseInfos", "diffuseMatrix",
  99331. ];
  99332. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  99333. var uniformBuffers = ["Material", "Scene"];
  99334. if (BABYLON.ImageProcessingConfiguration) {
  99335. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  99336. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  99337. }
  99338. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  99339. uniformsNames: uniforms,
  99340. uniformBuffersNames: uniformBuffers,
  99341. samplers: samplers,
  99342. defines: defines,
  99343. maxSimultaneousLights: this._maxSimultaneousLights
  99344. });
  99345. var onCompiled = function (effect) {
  99346. if (_this.onCompiled) {
  99347. _this.onCompiled(effect);
  99348. }
  99349. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  99350. };
  99351. var join = defines.toString();
  99352. subMesh.setEffect(scene.getEngine().createEffect("background", {
  99353. attributes: attribs,
  99354. uniformsNames: uniforms,
  99355. uniformBuffersNames: uniformBuffers,
  99356. samplers: samplers,
  99357. defines: join,
  99358. fallbacks: fallbacks,
  99359. onCompiled: onCompiled,
  99360. onError: this.onError,
  99361. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  99362. }, engine), defines);
  99363. this.buildUniformLayout();
  99364. }
  99365. if (!subMesh.effect || !subMesh.effect.isReady()) {
  99366. return false;
  99367. }
  99368. defines._renderId = scene.getRenderId();
  99369. this._wasPreviouslyReady = true;
  99370. return true;
  99371. };
  99372. /**
  99373. * Compute the primary color according to the chosen perceptual color.
  99374. */
  99375. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  99376. if (!this.__perceptualColor) {
  99377. return;
  99378. }
  99379. this._primaryColor.copyFrom(this.__perceptualColor);
  99380. // Revert gamma space.
  99381. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  99382. // Revert image processing configuration.
  99383. if (this._imageProcessingConfiguration) {
  99384. // Revert Exposure.
  99385. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  99386. }
  99387. this._computePrimaryColors();
  99388. };
  99389. /**
  99390. * Compute the highlights and shadow colors according to their chosen levels.
  99391. */
  99392. BackgroundMaterial.prototype._computePrimaryColors = function () {
  99393. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  99394. return;
  99395. }
  99396. // Find the highlight color based on the configuration.
  99397. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  99398. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  99399. // Find the shadow color based on the configuration.
  99400. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  99401. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  99402. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  99403. };
  99404. /**
  99405. * Build the uniform buffer used in the material.
  99406. */
  99407. BackgroundMaterial.prototype.buildUniformLayout = function () {
  99408. // Order is important !
  99409. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  99410. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  99411. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  99412. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  99413. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  99414. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  99415. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  99416. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  99417. this._uniformBuffer.addUniform("pointSize", 1);
  99418. this._uniformBuffer.addUniform("shadowLevel", 1);
  99419. this._uniformBuffer.addUniform("alpha", 1);
  99420. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  99421. this._uniformBuffer.addUniform("vReflectionControl", 4);
  99422. this._uniformBuffer.create();
  99423. };
  99424. /**
  99425. * Unbind the material.
  99426. */
  99427. BackgroundMaterial.prototype.unbind = function () {
  99428. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  99429. this._uniformBuffer.setTexture("diffuseSampler", null);
  99430. }
  99431. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  99432. this._uniformBuffer.setTexture("reflectionSampler", null);
  99433. }
  99434. _super.prototype.unbind.call(this);
  99435. };
  99436. /**
  99437. * Bind only the world matrix to the material.
  99438. * @param world The world matrix to bind.
  99439. */
  99440. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  99441. this._activeEffect.setMatrix("world", world);
  99442. };
  99443. /**
  99444. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  99445. * @param world The world matrix to bind.
  99446. * @param subMesh The submesh to bind for.
  99447. */
  99448. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  99449. var scene = this.getScene();
  99450. var defines = subMesh._materialDefines;
  99451. if (!defines) {
  99452. return;
  99453. }
  99454. var effect = subMesh.effect;
  99455. if (!effect) {
  99456. return;
  99457. }
  99458. this._activeEffect = effect;
  99459. // Matrices
  99460. this.bindOnlyWorldMatrix(world);
  99461. // Bones
  99462. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  99463. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  99464. if (mustRebind) {
  99465. this._uniformBuffer.bindToEffect(effect, "Material");
  99466. this.bindViewProjection(effect);
  99467. var reflectionTexture = this._reflectionTexture;
  99468. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  99469. // Texture uniforms
  99470. if (scene.texturesEnabled) {
  99471. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99472. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  99473. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  99474. }
  99475. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99476. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  99477. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  99478. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  99479. }
  99480. }
  99481. if (this.shadowLevel > 0) {
  99482. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  99483. }
  99484. this._uniformBuffer.updateFloat("alpha", this.alpha);
  99485. // Point size
  99486. if (this.pointsCloud) {
  99487. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  99488. }
  99489. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  99490. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  99491. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  99492. }
  99493. else {
  99494. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  99495. }
  99496. }
  99497. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  99498. // Textures
  99499. if (scene.texturesEnabled) {
  99500. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99501. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  99502. }
  99503. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99504. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  99505. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99506. }
  99507. else if (!defines.REFLECTIONBLUR) {
  99508. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99509. }
  99510. else {
  99511. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  99512. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  99513. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  99514. }
  99515. if (defines.REFLECTIONFRESNEL) {
  99516. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  99517. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  99518. }
  99519. }
  99520. }
  99521. // Clip plane
  99522. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  99523. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  99524. }
  99525. if (mustRebind || !this.isFrozen) {
  99526. if (scene.lightsEnabled) {
  99527. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  99528. }
  99529. // View
  99530. this.bindView(effect);
  99531. // Fog
  99532. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  99533. // image processing
  99534. if (this._imageProcessingConfiguration) {
  99535. this._imageProcessingConfiguration.bind(this._activeEffect);
  99536. }
  99537. }
  99538. this._uniformBuffer.update();
  99539. this._afterBind(mesh);
  99540. };
  99541. /**
  99542. * Dispose the material.
  99543. * @param forceDisposeEffect Force disposal of the associated effect.
  99544. * @param forceDisposeTextures Force disposal of the associated textures.
  99545. */
  99546. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  99547. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  99548. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  99549. if (forceDisposeTextures) {
  99550. if (this.diffuseTexture) {
  99551. this.diffuseTexture.dispose();
  99552. }
  99553. if (this.reflectionTexture) {
  99554. this.reflectionTexture.dispose();
  99555. }
  99556. }
  99557. this._renderTargets.dispose();
  99558. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99559. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99560. }
  99561. _super.prototype.dispose.call(this, forceDisposeEffect);
  99562. };
  99563. /**
  99564. * Clones the material.
  99565. * @param name The cloned name.
  99566. * @returns The cloned material.
  99567. */
  99568. BackgroundMaterial.prototype.clone = function (name) {
  99569. var _this = this;
  99570. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  99571. };
  99572. /**
  99573. * Serializes the current material to its JSON representation.
  99574. * @returns The JSON representation.
  99575. */
  99576. BackgroundMaterial.prototype.serialize = function () {
  99577. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99578. serializationObject.customType = "BABYLON.BackgroundMaterial";
  99579. return serializationObject;
  99580. };
  99581. /**
  99582. * Gets the class name of the material
  99583. * @returns "BackgroundMaterial"
  99584. */
  99585. BackgroundMaterial.prototype.getClassName = function () {
  99586. return "BackgroundMaterial";
  99587. };
  99588. /**
  99589. * Parse a JSON input to create back a background material.
  99590. * @param source The JSON data to parse
  99591. * @param scene The scene to create the parsed material in
  99592. * @param rootUrl The root url of the assets the material depends upon
  99593. * @returns the instantiated BackgroundMaterial.
  99594. */
  99595. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  99596. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  99597. };
  99598. /**
  99599. * Standard reflectance value at parallel view angle.
  99600. */
  99601. BackgroundMaterial.StandardReflectance0 = 0.05;
  99602. /**
  99603. * Standard reflectance value at grazing angle.
  99604. */
  99605. BackgroundMaterial.StandardReflectance90 = 0.5;
  99606. __decorate([
  99607. BABYLON.serializeAsColor3()
  99608. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  99609. __decorate([
  99610. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99611. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  99612. __decorate([
  99613. BABYLON.serializeAsColor3()
  99614. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  99615. __decorate([
  99616. BABYLON.serialize()
  99617. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  99618. __decorate([
  99619. BABYLON.serialize()
  99620. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  99621. __decorate([
  99622. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99623. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  99624. __decorate([
  99625. BABYLON.serializeAsTexture()
  99626. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  99627. __decorate([
  99628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99629. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  99630. __decorate([
  99631. BABYLON.serialize()
  99632. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  99633. __decorate([
  99634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99635. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  99636. __decorate([
  99637. BABYLON.serializeAsTexture()
  99638. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  99639. __decorate([
  99640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99641. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  99642. __decorate([
  99643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99644. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  99645. __decorate([
  99646. BABYLON.serialize()
  99647. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  99648. __decorate([
  99649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99650. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  99651. __decorate([
  99652. BABYLON.serializeAsVector3()
  99653. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  99654. __decorate([
  99655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99656. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  99657. __decorate([
  99658. BABYLON.serialize()
  99659. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  99660. __decorate([
  99661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99662. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  99663. __decorate([
  99664. BABYLON.serialize()
  99665. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  99666. __decorate([
  99667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99668. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  99669. __decorate([
  99670. BABYLON.serialize()
  99671. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  99672. __decorate([
  99673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99674. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  99675. __decorate([
  99676. BABYLON.serialize()
  99677. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  99678. __decorate([
  99679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99680. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  99681. __decorate([
  99682. BABYLON.serialize()
  99683. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  99684. __decorate([
  99685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99686. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  99687. __decorate([
  99688. BABYLON.serialize()
  99689. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  99690. __decorate([
  99691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99692. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  99693. __decorate([
  99694. BABYLON.serialize()
  99695. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  99696. __decorate([
  99697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99698. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  99699. __decorate([
  99700. BABYLON.serialize()
  99701. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  99702. __decorate([
  99703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99704. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  99705. __decorate([
  99706. BABYLON.serialize()
  99707. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  99708. __decorate([
  99709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99710. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  99711. __decorate([
  99712. BABYLON.serializeAsImageProcessingConfiguration()
  99713. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  99714. return BackgroundMaterial;
  99715. }(BABYLON.PushMaterial));
  99716. BABYLON.BackgroundMaterial = BackgroundMaterial;
  99717. })(BABYLON || (BABYLON = {}));
  99718. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  99719. var __assign = (this && this.__assign) || Object.assign || function(t) {
  99720. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99721. s = arguments[i];
  99722. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99723. t[p] = s[p];
  99724. }
  99725. return t;
  99726. };
  99727. var BABYLON;
  99728. (function (BABYLON) {
  99729. /**
  99730. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  99731. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  99732. * It also helps with the default setup of your imageProcessing configuration.
  99733. */
  99734. var EnvironmentHelper = /** @class */ (function () {
  99735. /**
  99736. * constructor
  99737. * @param options
  99738. * @param scene The scene to add the material to
  99739. */
  99740. function EnvironmentHelper(options, scene) {
  99741. var _this = this;
  99742. this._errorHandler = function (message, exception) {
  99743. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  99744. };
  99745. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  99746. this._scene = scene;
  99747. this.onErrorObservable = new BABYLON.Observable();
  99748. this._setupBackground();
  99749. this._setupImageProcessing();
  99750. }
  99751. /**
  99752. * Creates the default options for the helper.
  99753. */
  99754. EnvironmentHelper._getDefaultOptions = function () {
  99755. return {
  99756. createGround: true,
  99757. groundSize: 15,
  99758. groundTexture: this._groundTextureCDNUrl,
  99759. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99760. groundOpacity: 0.9,
  99761. enableGroundShadow: true,
  99762. groundShadowLevel: 0.5,
  99763. enableGroundMirror: false,
  99764. groundMirrorSizeRatio: 0.3,
  99765. groundMirrorBlurKernel: 64,
  99766. groundMirrorAmount: 1,
  99767. groundMirrorFresnelWeight: 1,
  99768. groundMirrorFallOffDistance: 0,
  99769. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  99770. groundYBias: 0.00001,
  99771. createSkybox: true,
  99772. skyboxSize: 20,
  99773. skyboxTexture: this._skyboxTextureCDNUrl,
  99774. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99775. backgroundYRotation: 0,
  99776. sizeAuto: true,
  99777. rootPosition: BABYLON.Vector3.Zero(),
  99778. setupImageProcessing: true,
  99779. environmentTexture: this._environmentTextureCDNUrl,
  99780. cameraExposure: 0.8,
  99781. cameraContrast: 1.2,
  99782. toneMappingEnabled: true,
  99783. };
  99784. };
  99785. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  99786. /**
  99787. * Gets the root mesh created by the helper.
  99788. */
  99789. get: function () {
  99790. return this._rootMesh;
  99791. },
  99792. enumerable: true,
  99793. configurable: true
  99794. });
  99795. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  99796. /**
  99797. * Gets the skybox created by the helper.
  99798. */
  99799. get: function () {
  99800. return this._skybox;
  99801. },
  99802. enumerable: true,
  99803. configurable: true
  99804. });
  99805. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  99806. /**
  99807. * Gets the skybox texture created by the helper.
  99808. */
  99809. get: function () {
  99810. return this._skyboxTexture;
  99811. },
  99812. enumerable: true,
  99813. configurable: true
  99814. });
  99815. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  99816. /**
  99817. * Gets the skybox material created by the helper.
  99818. */
  99819. get: function () {
  99820. return this._skyboxMaterial;
  99821. },
  99822. enumerable: true,
  99823. configurable: true
  99824. });
  99825. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  99826. /**
  99827. * Gets the ground mesh created by the helper.
  99828. */
  99829. get: function () {
  99830. return this._ground;
  99831. },
  99832. enumerable: true,
  99833. configurable: true
  99834. });
  99835. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  99836. /**
  99837. * Gets the ground texture created by the helper.
  99838. */
  99839. get: function () {
  99840. return this._groundTexture;
  99841. },
  99842. enumerable: true,
  99843. configurable: true
  99844. });
  99845. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  99846. /**
  99847. * Gets the ground mirror created by the helper.
  99848. */
  99849. get: function () {
  99850. return this._groundMirror;
  99851. },
  99852. enumerable: true,
  99853. configurable: true
  99854. });
  99855. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  99856. /**
  99857. * Gets the ground mirror render list to helps pushing the meshes
  99858. * you wish in the ground reflection.
  99859. */
  99860. get: function () {
  99861. if (this._groundMirror) {
  99862. return this._groundMirror.renderList;
  99863. }
  99864. return null;
  99865. },
  99866. enumerable: true,
  99867. configurable: true
  99868. });
  99869. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  99870. /**
  99871. * Gets the ground material created by the helper.
  99872. */
  99873. get: function () {
  99874. return this._groundMaterial;
  99875. },
  99876. enumerable: true,
  99877. configurable: true
  99878. });
  99879. /**
  99880. * Updates the background according to the new options
  99881. * @param options
  99882. */
  99883. EnvironmentHelper.prototype.updateOptions = function (options) {
  99884. var newOptions = __assign({}, this._options, options);
  99885. if (this._ground && !newOptions.createGround) {
  99886. this._ground.dispose();
  99887. this._ground = null;
  99888. }
  99889. if (this._groundMaterial && !newOptions.createGround) {
  99890. this._groundMaterial.dispose();
  99891. this._groundMaterial = null;
  99892. }
  99893. if (this._groundTexture) {
  99894. if (this._options.groundTexture != newOptions.groundTexture) {
  99895. this._groundTexture.dispose();
  99896. this._groundTexture = null;
  99897. }
  99898. }
  99899. if (this._skybox && !newOptions.createSkybox) {
  99900. this._skybox.dispose();
  99901. this._skybox = null;
  99902. }
  99903. if (this._skyboxMaterial && !newOptions.createSkybox) {
  99904. this._skyboxMaterial.dispose();
  99905. this._skyboxMaterial = null;
  99906. }
  99907. if (this._skyboxTexture) {
  99908. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  99909. this._skyboxTexture.dispose();
  99910. this._skyboxTexture = null;
  99911. }
  99912. }
  99913. if (this._groundMirror && !newOptions.enableGroundMirror) {
  99914. this._groundMirror.dispose();
  99915. this._groundMirror = null;
  99916. }
  99917. if (this._scene.environmentTexture) {
  99918. if (this._options.environmentTexture != newOptions.environmentTexture) {
  99919. this._scene.environmentTexture.dispose();
  99920. }
  99921. }
  99922. this._options = newOptions;
  99923. this._setupBackground();
  99924. this._setupImageProcessing();
  99925. };
  99926. /**
  99927. * Sets the primary color of all the available elements.
  99928. * @param color the main color to affect to the ground and the background
  99929. */
  99930. EnvironmentHelper.prototype.setMainColor = function (color) {
  99931. if (this.groundMaterial) {
  99932. this.groundMaterial.primaryColor = color;
  99933. }
  99934. if (this.skyboxMaterial) {
  99935. this.skyboxMaterial.primaryColor = color;
  99936. }
  99937. if (this.groundMirror) {
  99938. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  99939. }
  99940. };
  99941. /**
  99942. * Setup the image processing according to the specified options.
  99943. */
  99944. EnvironmentHelper.prototype._setupImageProcessing = function () {
  99945. if (this._options.setupImageProcessing) {
  99946. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  99947. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  99948. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  99949. this._setupEnvironmentTexture();
  99950. }
  99951. };
  99952. /**
  99953. * Setup the environment texture according to the specified options.
  99954. */
  99955. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  99956. if (this._scene.environmentTexture) {
  99957. return;
  99958. }
  99959. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  99960. this._scene.environmentTexture = this._options.environmentTexture;
  99961. return;
  99962. }
  99963. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  99964. this._scene.environmentTexture = environmentTexture;
  99965. };
  99966. /**
  99967. * Setup the background according to the specified options.
  99968. */
  99969. EnvironmentHelper.prototype._setupBackground = function () {
  99970. if (!this._rootMesh) {
  99971. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  99972. }
  99973. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  99974. var sceneSize = this._getSceneSize();
  99975. if (this._options.createGround) {
  99976. this._setupGround(sceneSize);
  99977. this._setupGroundMaterial();
  99978. this._setupGroundDiffuseTexture();
  99979. if (this._options.enableGroundMirror) {
  99980. this._setupGroundMirrorTexture(sceneSize);
  99981. }
  99982. this._setupMirrorInGroundMaterial();
  99983. }
  99984. if (this._options.createSkybox) {
  99985. this._setupSkybox(sceneSize);
  99986. this._setupSkyboxMaterial();
  99987. this._setupSkyboxReflectionTexture();
  99988. }
  99989. this._rootMesh.position.x = sceneSize.rootPosition.x;
  99990. this._rootMesh.position.z = sceneSize.rootPosition.z;
  99991. this._rootMesh.position.y = sceneSize.rootPosition.y;
  99992. };
  99993. /**
  99994. * Get the scene sizes according to the setup.
  99995. */
  99996. EnvironmentHelper.prototype._getSceneSize = function () {
  99997. var _this = this;
  99998. var groundSize = this._options.groundSize;
  99999. var skyboxSize = this._options.skyboxSize;
  100000. var rootPosition = this._options.rootPosition;
  100001. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  100002. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  100003. }
  100004. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  100005. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  100006. });
  100007. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  100008. if (this._options.sizeAuto) {
  100009. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  100010. this._scene.activeCamera.upperRadiusLimit) {
  100011. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  100012. skyboxSize = groundSize;
  100013. }
  100014. var sceneDiagonalLenght = sceneDiagonal.length();
  100015. if (sceneDiagonalLenght > groundSize) {
  100016. groundSize = sceneDiagonalLenght * 2;
  100017. skyboxSize = groundSize;
  100018. }
  100019. // 10 % bigger.
  100020. groundSize *= 1.1;
  100021. skyboxSize *= 1.5;
  100022. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  100023. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  100024. }
  100025. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  100026. };
  100027. /**
  100028. * Setup the ground according to the specified options.
  100029. */
  100030. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  100031. var _this = this;
  100032. if (!this._ground) {
  100033. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  100034. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  100035. this._ground.parent = this._rootMesh;
  100036. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  100037. }
  100038. this._ground.receiveShadows = this._options.enableGroundShadow;
  100039. };
  100040. /**
  100041. * Setup the ground material according to the specified options.
  100042. */
  100043. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  100044. if (!this._groundMaterial) {
  100045. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  100046. }
  100047. this._groundMaterial.alpha = this._options.groundOpacity;
  100048. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  100049. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  100050. this._groundMaterial.primaryColor = this._options.groundColor;
  100051. this._groundMaterial.useRGBColor = false;
  100052. this._groundMaterial.enableNoise = true;
  100053. if (this._ground) {
  100054. this._ground.material = this._groundMaterial;
  100055. }
  100056. };
  100057. /**
  100058. * Setup the ground diffuse texture according to the specified options.
  100059. */
  100060. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  100061. if (!this._groundMaterial) {
  100062. return;
  100063. }
  100064. if (this._groundTexture) {
  100065. return;
  100066. }
  100067. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  100068. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  100069. return;
  100070. }
  100071. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  100072. diffuseTexture.gammaSpace = false;
  100073. diffuseTexture.hasAlpha = true;
  100074. this._groundMaterial.diffuseTexture = diffuseTexture;
  100075. };
  100076. /**
  100077. * Setup the ground mirror texture according to the specified options.
  100078. */
  100079. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  100080. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100081. if (!this._groundMirror) {
  100082. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  100083. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  100084. this._groundMirror.anisotropicFilteringLevel = 1;
  100085. this._groundMirror.wrapU = wrapping;
  100086. this._groundMirror.wrapV = wrapping;
  100087. this._groundMirror.gammaSpace = false;
  100088. if (this._groundMirror.renderList) {
  100089. for (var i = 0; i < this._scene.meshes.length; i++) {
  100090. var mesh = this._scene.meshes[i];
  100091. if (mesh !== this._ground &&
  100092. mesh !== this._skybox &&
  100093. mesh !== this._rootMesh) {
  100094. this._groundMirror.renderList.push(mesh);
  100095. }
  100096. }
  100097. }
  100098. }
  100099. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  100100. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  100101. };
  100102. /**
  100103. * Setup the ground to receive the mirror texture.
  100104. */
  100105. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  100106. if (this._groundMaterial) {
  100107. this._groundMaterial.reflectionTexture = this._groundMirror;
  100108. this._groundMaterial.reflectionFresnel = true;
  100109. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  100110. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  100111. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  100112. }
  100113. };
  100114. /**
  100115. * Setup the skybox according to the specified options.
  100116. */
  100117. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  100118. var _this = this;
  100119. if (!this._skybox) {
  100120. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  100121. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  100122. }
  100123. this._skybox.parent = this._rootMesh;
  100124. };
  100125. /**
  100126. * Setup the skybox material according to the specified options.
  100127. */
  100128. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  100129. if (!this._skybox) {
  100130. return;
  100131. }
  100132. if (!this._skyboxMaterial) {
  100133. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  100134. }
  100135. this._skyboxMaterial.useRGBColor = false;
  100136. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  100137. this._skyboxMaterial.enableNoise = true;
  100138. this._skybox.material = this._skyboxMaterial;
  100139. };
  100140. /**
  100141. * Setup the skybox reflection texture according to the specified options.
  100142. */
  100143. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  100144. if (!this._skyboxMaterial) {
  100145. return;
  100146. }
  100147. if (this._skyboxTexture) {
  100148. return;
  100149. }
  100150. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  100151. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  100152. return;
  100153. }
  100154. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  100155. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  100156. this._skyboxTexture.gammaSpace = false;
  100157. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  100158. };
  100159. /**
  100160. * Dispose all the elements created by the Helper.
  100161. */
  100162. EnvironmentHelper.prototype.dispose = function () {
  100163. if (this._groundMaterial) {
  100164. this._groundMaterial.dispose(true, true);
  100165. }
  100166. if (this._skyboxMaterial) {
  100167. this._skyboxMaterial.dispose(true, true);
  100168. }
  100169. this._rootMesh.dispose(false);
  100170. };
  100171. /**
  100172. * Default ground texture URL.
  100173. */
  100174. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  100175. /**
  100176. * Default skybox texture URL.
  100177. */
  100178. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  100179. /**
  100180. * Default environment texture URL.
  100181. */
  100182. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  100183. return EnvironmentHelper;
  100184. }());
  100185. BABYLON.EnvironmentHelper = EnvironmentHelper;
  100186. })(BABYLON || (BABYLON = {}));
  100187. //# sourceMappingURL=babylon.environmentHelper.js.map
  100188. var BABYLON;
  100189. (function (BABYLON) {
  100190. /**
  100191. * This class is made for on one-liner static method to help creating particle systems.
  100192. */
  100193. var ParticleHelper = /** @class */ (function () {
  100194. function ParticleHelper() {
  100195. }
  100196. /**
  100197. * This is the main static method (one-liner) of this helper to create different particle systems.
  100198. * @param type This string represents the type to the particle system to create
  100199. * @param emitter The object where the particle system will start to emit from.
  100200. * @param scene The scene where the particle system should live.
  100201. * @param gpu If the system will use gpu.
  100202. * @returns the ParticleSystem created.
  100203. */
  100204. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  100205. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  100206. if (gpu === void 0) { gpu = false; }
  100207. return new Promise(function (resolve, reject) {
  100208. if (!scene) {
  100209. scene = BABYLON.Engine.LastCreatedScene;
  100210. ;
  100211. }
  100212. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  100213. return reject("Particle system with GPU is not supported.");
  100214. }
  100215. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  100216. var newData = JSON.parse(data.toString());
  100217. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  100218. }, undefined, undefined, undefined, function (req, exception) {
  100219. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  100220. });
  100221. });
  100222. };
  100223. /**
  100224. * Static function used to create a new particle system from a IParticleSystemData
  100225. * @param data defines the source data
  100226. * @param scene defines the hosting scene
  100227. * @param emitter defines the particle emitter
  100228. * @returns a new ParticleSystem based on referenced data
  100229. */
  100230. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  100231. // Create a particle system
  100232. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  100233. // Where the particles come from
  100234. system.emitter = emitter; // the starting object, the emitter
  100235. ParticleHelper.UpdateSystem(system, data, scene);
  100236. return system;
  100237. };
  100238. /**
  100239. * Static function used to update a particle system from a IParticleSystemData
  100240. * @param system defines the particle system to update
  100241. * @param data defines the source data
  100242. * @param scene defines the hosting scene
  100243. */
  100244. ParticleHelper.UpdateSystem = function (system, data, scene) {
  100245. // Texture of each particle
  100246. if (data.textureFile) {
  100247. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  100248. }
  100249. // Colors of all particles
  100250. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  100251. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  100252. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  100253. // Size of each particle (random between...
  100254. system.minSize = data.minSize;
  100255. system.maxSize = data.maxSize;
  100256. system.minScaleX = data.minScaleX;
  100257. system.maxScaleX = data.maxScaleX;
  100258. system.minScaleY = data.minScaleY;
  100259. system.maxScaleY = data.maxScaleY;
  100260. // Life time of each particle (random between...
  100261. system.minLifeTime = data.minLifeTime;
  100262. system.maxLifeTime = data.maxLifeTime;
  100263. // Emission rate
  100264. system.emitRate = data.emitRate;
  100265. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  100266. system.blendMode = data.blendMode;
  100267. // Set the gravity of all particles
  100268. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  100269. // Angular speed, in radians
  100270. system.minAngularSpeed = data.minAngularSpeed;
  100271. system.maxAngularSpeed = data.maxAngularSpeed;
  100272. // Speed
  100273. system.minEmitPower = data.minEmitPower;
  100274. system.maxEmitPower = data.maxEmitPower;
  100275. system.updateSpeed = data.updateSpeed;
  100276. switch (data.emitterType) {
  100277. case "box":
  100278. if (!data.direction1 || !data.direction2) {
  100279. throw new Error("Directions are missing in this particle system.");
  100280. }
  100281. if (!data.minEmitBox || !data.maxEmitBox) {
  100282. throw new Error("EmitBox is missing in this particle system.");
  100283. }
  100284. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  100285. break;
  100286. case "sphere":
  100287. system.createSphereEmitter(data.radius);
  100288. break;
  100289. case "directed_sphere":
  100290. if (!data.direction1 || !data.direction2) {
  100291. throw new Error("Directions are missing in this particle system.");
  100292. }
  100293. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  100294. break;
  100295. case "cone":
  100296. system.createConeEmitter(data.radius, data.angle);
  100297. break;
  100298. default:
  100299. break;
  100300. }
  100301. };
  100302. /**
  100303. * Static function used to export a particle system to a IParticleSystemData variable.
  100304. * Please note that texture file name is not exported and must be added manually
  100305. * @param system defines the particle system to export
  100306. */
  100307. ParticleHelper.ExportSystem = function (system) {
  100308. var outData = {};
  100309. // Colors of all particles
  100310. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  100311. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  100312. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  100313. // Size of each particle (random between...
  100314. outData.minSize = system.minSize;
  100315. outData.maxSize = system.maxSize;
  100316. outData.minScaleX = system.minScaleX;
  100317. outData.maxScaleX = system.maxScaleX;
  100318. outData.minScaleY = system.minScaleY;
  100319. outData.maxScaleY = system.maxScaleY;
  100320. // Life time of each particle (random between...
  100321. outData.minLifeTime = system.minLifeTime;
  100322. outData.maxLifeTime = system.maxLifeTime;
  100323. // Emission rate
  100324. outData.emitRate = system.emitRate;
  100325. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  100326. outData.blendMode = system.blendMode;
  100327. // Set the gravity of all particles
  100328. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  100329. // Angular speed, in radians
  100330. outData.minAngularSpeed = system.minAngularSpeed;
  100331. outData.maxAngularSpeed = system.maxAngularSpeed;
  100332. // Speed
  100333. outData.minEmitPower = system.minEmitPower;
  100334. outData.maxEmitPower = system.maxEmitPower;
  100335. outData.updateSpeed = system.updateSpeed;
  100336. switch (system.particleEmitterType.getClassName()) {
  100337. case "BoxEmitter":
  100338. outData.emitterType = "box";
  100339. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  100340. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  100341. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  100342. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  100343. break;
  100344. case "SphereParticleEmitter":
  100345. outData.emitterType = "sphere";
  100346. outData.radius = system.particleEmitterType.radius;
  100347. break;
  100348. case "SphereDirectedParticleEmitter":
  100349. outData.emitterType = "directed_sphere";
  100350. var sphereDirectedParticleEmitter = system.particleEmitterType;
  100351. outData.radius = sphereDirectedParticleEmitter.radius;
  100352. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  100353. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  100354. break;
  100355. case "ConeEmitter":
  100356. outData.emitterType = "cone";
  100357. outData.radius = system.particleEmitterType.radius;
  100358. outData.angle = system.particleEmitterType.angle;
  100359. break;
  100360. default:
  100361. break;
  100362. }
  100363. return outData;
  100364. };
  100365. /**
  100366. * Base Assets URL.
  100367. */
  100368. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  100369. return ParticleHelper;
  100370. }());
  100371. BABYLON.ParticleHelper = ParticleHelper;
  100372. })(BABYLON || (BABYLON = {}));
  100373. //# sourceMappingURL=babylon.particleHelper.js.map
  100374. var BABYLON;
  100375. (function (BABYLON) {
  100376. /**
  100377. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  100378. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  100379. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  100380. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100381. */
  100382. var VideoDome = /** @class */ (function (_super) {
  100383. __extends(VideoDome, _super);
  100384. /**
  100385. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  100386. * @param name Element's name, child elements will append suffixes for their own names.
  100387. * @param urlsOrVideo defines the url(s) or the video element to use
  100388. * @param options An object containing optional or exposed sub element properties
  100389. */
  100390. function VideoDome(name, urlsOrVideo, options, scene) {
  100391. var _this = _super.call(this, name, scene) || this;
  100392. // set defaults and manage values
  100393. name = name || "videoDome";
  100394. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100395. options.clickToPlay = Boolean(options.clickToPlay);
  100396. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  100397. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  100398. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100399. // create
  100400. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  100401. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100402. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  100403. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100404. flat: false,
  100405. radius: options.size,
  100406. subdivisions: options.resolution,
  100407. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100408. }, scene);
  100409. // configure material
  100410. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100411. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100412. material.reflectionTexture = _this._videoTexture;
  100413. material.useEquirectangularFOV = true;
  100414. material.fovMultiplier = 1.0;
  100415. // configure mesh
  100416. _this._mesh.material = material;
  100417. _this._mesh.parent = _this;
  100418. // optional configuration
  100419. if (options.clickToPlay) {
  100420. scene.onPointerUp = function () {
  100421. _this._videoTexture.video.play();
  100422. };
  100423. }
  100424. return _this;
  100425. }
  100426. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  100427. /**
  100428. * Gets the video texture being displayed on the sphere
  100429. */
  100430. get: function () {
  100431. return this._videoTexture;
  100432. },
  100433. enumerable: true,
  100434. configurable: true
  100435. });
  100436. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  100437. /**
  100438. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100439. * Also see the options.resolution property.
  100440. */
  100441. get: function () {
  100442. return this._material.fovMultiplier;
  100443. },
  100444. set: function (value) {
  100445. this._material.fovMultiplier = value;
  100446. },
  100447. enumerable: true,
  100448. configurable: true
  100449. });
  100450. /**
  100451. * Releases resources associated with this node.
  100452. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100453. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100454. */
  100455. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100456. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100457. this._videoTexture.dispose();
  100458. this._mesh.dispose();
  100459. this._material.dispose();
  100460. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100461. };
  100462. return VideoDome;
  100463. }(BABYLON.Node));
  100464. BABYLON.VideoDome = VideoDome;
  100465. })(BABYLON || (BABYLON = {}));
  100466. //# sourceMappingURL=babylon.videoDome.js.map
  100467. var BABYLON;
  100468. (function (BABYLON) {
  100469. /**
  100470. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  100471. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  100472. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  100473. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100474. */
  100475. var PhotoDome = /** @class */ (function (_super) {
  100476. __extends(PhotoDome, _super);
  100477. /**
  100478. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  100479. * @param name Element's name, child elements will append suffixes for their own names.
  100480. * @param urlsOfPhoto define the url of the photo to display
  100481. * @param options An object containing optional or exposed sub element properties
  100482. */
  100483. function PhotoDome(name, urlOfPhoto, options, scene) {
  100484. var _this = _super.call(this, name, scene) || this;
  100485. // set defaults and manage values
  100486. name = name || "photoDome";
  100487. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100488. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100489. // create
  100490. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100491. var texture = _this._photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  100492. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100493. flat: false,
  100494. radius: options.size,
  100495. subdivisions: options.resolution,
  100496. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100497. }, scene);
  100498. // configure material
  100499. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100500. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100501. material.reflectionTexture = _this._photoTexture;
  100502. material.useEquirectangularFOV = true;
  100503. material.fovMultiplier = 1.0;
  100504. // configure mesh
  100505. _this._mesh.material = material;
  100506. _this._mesh.parent = _this;
  100507. return _this;
  100508. }
  100509. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  100510. /**
  100511. * Gets the texture being displayed on the sphere
  100512. */
  100513. get: function () {
  100514. return this._photoTexture;
  100515. },
  100516. enumerable: true,
  100517. configurable: true
  100518. });
  100519. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  100520. /**
  100521. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100522. * Also see the options.resolution property.
  100523. */
  100524. get: function () {
  100525. return this._material.fovMultiplier;
  100526. },
  100527. set: function (value) {
  100528. this._material.fovMultiplier = value;
  100529. },
  100530. enumerable: true,
  100531. configurable: true
  100532. });
  100533. /**
  100534. * Releases resources associated with this node.
  100535. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100536. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100537. */
  100538. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100539. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100540. this._photoTexture.dispose();
  100541. this._mesh.dispose();
  100542. this._material.dispose();
  100543. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100544. };
  100545. return PhotoDome;
  100546. }(BABYLON.Node));
  100547. BABYLON.PhotoDome = PhotoDome;
  100548. })(BABYLON || (BABYLON = {}));
  100549. //# sourceMappingURL=babylon.photoDome.js.map
  100550. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec3 options;\nattribute vec2 size;\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; \nvec2 cornerPos;\nfloat angle=options.x;\nvec2 offset=options.yz;\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); \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 vec3 size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nin vec2 angle;\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);\nvec2 cornerPos=offset*size.yz*size.x;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\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 scaleRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\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 coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin vec3 size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout vec3 outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\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=vec3(0.,0.,0.);\noutDirection=direction;\noutAngle=angle;\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.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\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 (coneAngle == 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;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  100551. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=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};"};
  100552. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  100553. globalObject["BABYLON"] = BABYLON;
  100554. //backwards compatibility
  100555. if(typeof earcut !== 'undefined') {
  100556. globalObject["Earcut"] = {
  100557. earcut: earcut
  100558. };
  100559. }
  100560. return BABYLON;
  100561. });